Search code examples
asp.net-mvcangularjsasp.net-mvc-4angularjs-routing

urls and angularjs with mvc


I have a problem with my angular routes when entering the URL directly in the URL bar of the browser.

What happens is this. When my app loads up I call a single MVC controller which loads a MVC view which holds inside it a ng-view. This then in turn loads my main angular view. This works great. I then select some options and click save which then routes me to my success view. (Angular takes good care of this). However, when I try to go directly to my success view I get a 404 error returned from the server.

Now I know this is because there isn't a route in MVC that takes care of this for me, but there is a route that should redirect to my main MVC index view which in turn loads up my angular app.

routes.MapRoute(
    name: "Settings",
    url: "{controller}/{*catchall}",
    defaults: new { controller = "Settings", action = "Index" }
);

Now I would expect that when I refresh a page this controller would be called which should load up my angular app where the angular routing takes over and displays the correct view, but this doesn't happen at all.

My angular routes

parts of the URL omitted

angular.module('app', ['ngRoute', 'restangular']).config([
    '$routeProvider', 'RestangularProvider', '$locationProvider', function ($routeProvider, RestangularProvider, $locationProvider) {
        $locationProvider.html5Mode(true);
        $routeProvider.
            when('/**/**/**/settings', {
                templateUrl: 'App/globalsettings/templates/globalsettings.html',
                controller: 'globalsettingsCtrl'
            }).
            when('/**/**/**/success', {
                templateUrl: 'App/globalsettings/templates/success.html',
            }).
            when('/**/**/**/error', {
                templateUrl: 'App/globalsettings/templates/error.html',
            }).
            otherwise({ redirectTo: '/**/**/**/settings' });

        RestangularProvider.setBaseUrl("api");
    }
]);

Can anyone answer as to why my routing fails when refreshing the page or entering the URL directly.


Solution

  • Your route will still get the controller from the url. So if you navigate to /success the route is extracting success as the controller name.

    You could try renaming the controller segment in the route, this way the controller will always get the default value Settings. For example defining the route as:

    routes.MapRoute(
        name: "Settings",
        url: "{angularController}/{*catchall}",
        defaults: new { controller = "Settings", action = "Index" }
    );
    

    You could rename that url segment to something that makes more sense to you, as long as it is not named controller.