Fixing AngularJS + MVC Routing Issues

hashratestore_icon-1Currently, I’m working on a hybrid AngularJS and MVC project, one of the tasks being to get rid of the # symbol from the URL. In pure AngularJS apps, this is very easily done by following the next two steps (and easily googled):

  1. Set up your base href in your index page: <head> <base href=”/”> </head>
  2. Add the following in your angular app config: $locationProvider.html5Mode(true)

 

The problem arises when you are in the .NET stack and using AngularJS with MVC. The above solution will still remove the # from URL, but page refresh won’t work. Why? This happens because MVC knows nothing about AngularJS routing and by following default MVC routing, it will look for an MVC page which doesn’t exist.

 

The workaround is to send all MVC page requests to a single MVC view, and to do that you have to add a route to catch all requests as follows:

  1. The base href has to set up in your _Layout page: <head> <base href=”/”> </head>
  2. In the RouteConfig.cs, which is found in the App_Start folder, you should insert the following route:

[code language=”javascript”]
// Very imp to include for Angular App to remove #
routes.MapRoute(
name: "App",
url: "{*url}",
defaults: new { controller = "Home", action = "Index" }
);
[/code]

 

If you have any MVC views that you need to load, you will have to add another route for them, as now with the above routing, all the other MVC views will be ignored. If you want to show a page from say the AboutController, you’ll have to add a custom route for the controller as the following:

[code language=”javascript”]
// This route allows access to the AboutController
routes.MapRoute(
name: "About",
url: "about/{action}",
defaults: new { controller = "About", action = "Index" }
);
);
[/code]

It’s important that you put this route before the Angular routing, else it will be ignored. Hope this will save you some time 🙂

No Responses

Leave a Reply

Your email address will not be published. Required fields are marked *