Routing not working when using areas in MVC.

November 5, 2017 at 5:29 PMMadestro

I recently came across a situation where I had two controllers named Home. One existed under an area and the other one under the normal Controllers folder.

The routes started misbehaving and sometimes they would fail.

I found a few articles about adding namespaces but that didn't seem to work.

After hours of searching and thinking, I figured it out. The namespaces have to match the location of the Controllers folder. Here is a sample to illustrate:

context.MapRoute(
                "Admin_default",
                "Admin/{controller}/{action}/{id}",
                new { controller = "System", action = "Index", id = UrlParameter.Optional}
                , new[] { "MyWebApp.Admin.Controllers" }
            );

 

Notice the namespace includes the the Controllers folder.

It's not just any name. It has to match your Controllers namespace exactly.

Posted in: ASP.NET MVC

Tags: ,

How to fix Visual Studio Could not evaluate Expression

October 11, 2016 at 1:16 PMMadestro

Sometimes you will come across a situation where you debug in Visual Studio and you are unable to look at the variables. You simply get a message that reads:

"Could not evaluate Expression"

Long story short, one of the reasons this happens is corrupt breakpoints.

Pull up your Breakpoint window and erase every single breakpoint you have. Compile and set your breakpoints again.

Problem solved. :-)

Posted in: ASP.NET MVC | General Development | Visual Studio

Tags:

Running Windows Authentication with IIS Express

August 6, 2015 at 10:18 AMMadestro

You may run into a situation where you have configured your site to run Windows authentication but you get an authentication error when you try to browse it during a debug session.

To fix this issue, you need to edit the Application Host file for IIS and enable Windows authentication. You can find the file here:

\My Documents\IISExpress\config\applicationhost.config

Find the <security> section inside the <system.webServer> node and enable Windows authentication as follows:

<system.webServer>
...
  <security>
...
    <authentication>
      <windowsAuthentication enabled="true" />
    </authentication>
...
  </security>
...
</system.webServer>

And that's all there is to it. :-)

Posted in: ASP.NET MVC | Visual Studio | Web Development

Tags:

Intellisense not working on views after migrating MVC application to Visual Studio 2013

January 8, 2014 at 11:28 AMMadestro

 

I recently migrated one of our MVC applications to Visual Studio 2013.

After the migration, Intellisense broke. It would not work for any view I opened. It wouldn't even recognize the @model directive.

Since part of the plan was to upgrade to the latest version of MVC (5 at the time of this writing), I decided to add the NuGet package and its dependencies. This didn't solve the problem either.

Eventually, I ended up creating a new test MVC project with Visual Studio 2013. I then took the pertinent sections from the web.config file under the Views folder and copied them over to my migrated project. I then closed and relaunched VS2012 and the solution.

That got Intellisense working again.

Keep in mind that if you do this, you will introduce some new dependencies, since the latest template uses the System.Web.Optimization namespace. I didn't try removing this namespace from the web.config but if you don't want the dependencies, you might be able to get away with removing it from the web.config.

Posted in: ASP.NET MVC | Visual Studio

Tags:

Getting an XSLT file to load when the site is hosted on a network share

November 25, 2013 at 10:53 AMMadestro

So I was working on a website the other day and had a bunch of XSLT templates that were used to produce HTML for e-mails.

Well, no e-mails were coming through. Further investigation revealed the issue to be that the XslCompiledTransform.Load() method call was failing with a System.IO.FileNotFound error.

When I looked at the  actual physical path for the file that resulted from the call to Server.MapPath(), I realized that the site was actually being hosted on a network share (e.g. \\someserver\sites\x\content\web\xsltfile.xslt)

 The issue in this case turned out to be Network Access permissions.

 You see, the issue with this setup is that the application pool runs under a particular identity (e.g. NetworkService). Because the file we are trying to read actually seats on a NETWORK share, the account the pool is running in does not have permissions to read the file so we need to authenticate. Unfortunately the error thrown is misleading since the path is correct. It's just that it cannot reach the file due to permissions.

There are ways in which you can perform authentication but that involves internal knowledge of the network share and more times than not it is less than ideal since most people use a hosting provider.

And then, after being transferred four times to someone else by RackSpace support, it hit me!...

If you keep your XSLT files within the public realm of your website, you can have it served to you by the web server.

In other words, simply consume it as a web resource. The XslCompiledTransform.Load() method supports a URI as a parameter (or string representing one):

string sampleAddress = "http://www.mysite.com/transforms/mytransform.xslt";
XslCompiledTransform transform = new XslCompiledTransform();
transform.Load(sampleAddress);

 

And that's all there is to it. Laughing

Posted in: ASP.NET MVC

Tags:

Why are my bootstrap scripts not rendering in MVC4?

May 1, 2013 at 2:59 PMMadestro

I recently decided to play with Bootstrap, a front-end framework for creating websites that are responsive to the type of device used to access them.

I was following an article I found in .NET Curry and everything was going well. For anyone new to Bootstrap, here is a quick overview of the steps to add Bootstrap to an ASP.NET MVC4 application:

  • Add Bootstrap NUGET package to MVC4 application
  • Update jQuery to the required version
  • Add Bootstrap bundles in BundleConfig.cs
  • Modify _layout.cshtml to include Bootstrap scripts and styles
  • Modify _layout.cshtml with the wireframe of your new Bootstrap design
  • Modify your pages based on Bootstrap

(Read the full article for details)

Strangely enough, the styles were not being applied. I did everything the article said!... why is it not working?...

Further examination revealed the Bootstrap scripts and CSS was not being outputted to the page.

After Googling for a while, I found the answer in StackOverflow.

It turns out the BundleCollection class (passed on as a parameter to the BundleConfig class from the Global.asax call) has an IgnoreList property which is an instance of the IgnoreList class that defines items or patterns to ignore. 

Conveniently (or not so) enough, it ignores the ".min" pattern. 

The solutions:

  1. Remove the .min from the script and style paths added in the BundleConfig.cs class, OR
  2. Call the Clear() method of the IgnoreList instance in order to remove the filters:
    • bundles.IgnoreList.Clear();

This will cause your Bootstrap scripts and styles to render as they should.

One more note for those of you getting started with Bootstrap:

Applying the NUGET package only adds the files needed to run bootstrap. It won't magically change your layout and/or pages. Once you get Bootstrap running, go get yourself a page design and/or theme and modify your pages accordingly.

Posted in: ASP.NET MVC

Tags:

Getting Ajax calls to work with MVC4

January 31, 2013 at 4:18 PMMadestro

I recently started working with MVC4. After (literally) cutting and pasting code from some other application I had worked on which used MVC3, I found my Ajax calls where no longer working. 

It took me about three hours of research to figure out what the issue was.

The JQuery libraries that are used for Ajax calls are loaded in a different manner now. In the past, you would include them one by one in your _layout file. With the new version, you need to introduce the right "bundle". 

If you look at the code generated by the VS template, you will see two calls that load stuff for you:

@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")

What you need to do is add the following two lines of code in order to load the JQuery includes:

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")

What's happening under the scenes is that there is now a new Bundle and Minification Framework in place. If you look at your App_Start folder, you will notice a file called BundleConfig.cs. This file contains bundle definitions that are used to load resources. You can read more about it here.

The bundle in question here is defined as follows:

bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.unobtrusive*",
                        "~/Scripts/jquery.validate*"));
 

Once these two files are loaded, your Ajax calls should start working again.

Hopefully this post will save you some Google time... you can find the source that solved my issue here.

Posted in: ASP.NET MVC

Tags:

ASP.NET MVC lifecycle

February 23, 2012 at 4:47 PMMadestro

I was working on something and needed to refer to the ASP.NET MVC lifecycle so I went out there and found the following information which I have compiled for your benefit:

Overview of the Lifecycle Steps

There are five main steps that happen when you make a request from an ASP.NET MVC website:

1. The RouteTable is Created

This first step happens only once when an ASP.NET application first starts. The RouteTable maps URLs to handlers.

2. The UrlRoutingModule Intercepts the Request

This second step happens whenever you make a request. The UrlRoutingModule intercepts every request and creates and executes the right handler.

3. The MvcHandler Executes

The MvcHandler creates a controller, passes the controller a ControllerContext, and executes the controller.

4. The Controller Executes

The controller determines which controller method to execute, builds a list of parameters, and executes the method.

5. The RenderView Method is Called

Typically, a controller method calls RenderView() to render content back to the browser. The Controller.RenderView() method delegates its work to a particular ViewEngine

Source: http://stackoverflow.com/questions/2355139/what-is-the-lifetime-of-a-asp-net-mvc-controller

I also found a chart by Steve Sanderson you can print and keep around your desk:

http://blog.stevensanderson.com/2009/10/08/aspnet-mvc-learning-resource-request-handling-pipeline-poster/

Posted in: ASP.NET MVC

Tags:

Ajax action link not calling the corresponding method in controller

January 30, 2012 at 2:38 PMMadestro

So I was working on an ASP.NET MVC application and stumbled upon a little situation that was driving me nuts. I had an action link which used a confirmation message box that would allow the user to delete a record. The code was straight forward but for some reason the action would not fire on the controller.

After trying a few things I realized I was using some boiler plate code that provided standard handlers for the events:

new AjaxOptions() { Confirm = "Are you sure you want to delete this record from the system?", UpdateTargetId = "Results", HttpMethod = "POST", LoadingElementId = "LoadingContainer", OnSuccess = "Ajax_OnSuccess", OnFailure = "Ajax_OnFailure", OnBegin = "Ajax_OnBegin", OnComplete = "Ajax_OnComplete" }

(Scroll to the right on the code line, notice the "Ajax_" event handlers)

The issue turned out to be that I had forgotten to include the script file with these functions into my page. Apparently, if you provide method names but do not provide the implementation, it breaks the call to the action.

I hope this saves someone else some time...

Posted in: ASP.NET MVC

Tags: