How to fix SPA AngularJS with ASP.NET MVC lose layout on refresh page

By FoxLearn 2/16/2024 7:41:49 AM   82
This post shows you how to fix the lost page layout when refreshing your page in ASP.NET MVC using AngularJS.

To fix SPA refresh page using routing with AngularJS, you should modify the configuration in the RouteConfig class as below.

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        name: "Home",
        url: "Home/{*.}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );

    routes.MapRoute(
        name: "Customer",
        url: "Customer/{*.}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}

We will override our route redirecting all routes to the Home controller with the Index action, you should set ng-view to Index.cshtml

Open your angularjs route, then modify your code as shown below

(function () {
    'use strict';
    var app = angular.module('app', [
        // Angular modules 
        'ngRoute'
        // Custom modules
        // 3rd Party Modules
    ]);
    app.config(function ($routeProvider, $locationProvider) {
        $routeProvider.when('/', {
            templateUrl: '/app/views/home/index.html'
        }).when('/Home/About', {
            templateUrl: '/app/views/home/about.html',
            controller: 'homeController'
        }).when('/Home/Contact', {
            templateUrl: '/app/views/home/contact.html'
        }).when('/Customer', {
            templateUrl: '/app/views/customer/index.html'
        }).otherwise({
            redirectTo: '/'
        });
        $locationProvider.hashPrefix('!').html5Mode({
            enabled: true,
            requireBase: false
        });
    });
})();

As you can see, the template i'm using is an html file extension instead of returning from PartialView in ASP.NET MVC and AngularJS Page Refresh Problems have been solved.

If your controller return View you get an error trying to load Angular more than once because it calls Index action in the Home controller again, you should return the PartialView but it will be losed layout when refreshing your page