Search code examples
angularjsasp.net-mvcentity-frameworkasp.net-web-apiangularjs-routing

Angular JS Routing is not working in ASP.NET MVC and Web API project


I have two main ASP.NET MVC controllers: Home and User. Home has an Index method that is returning an Index view which is main page for loading partial pages (User Detail, Facility, Login Page) in ng-view. Also, Index view is not using MVC layout. My solution explorer looks like this

[enter image description here](https://i.sstatic.net/UJYzQ.png)

Issue is, when I run application, partial pages are not loading in ng-View and URL is not forming correctly.

My Module.js looks like this

/// <reference path="../scripts/angular.js" />
var app = angular.module('ApplicationModule', ['ngRoute']);
app.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
    //alert('Im Config');
    $routeProvider.when('/Login',
        {
            templateUrl: 'User/Login',
            controller: 'LoginController'
        })
        .when('/Profile',
            {
                templateUrl: 'User/UserDetail',
                controller: 'ProfileController'
            })
        .when('/Facility',
            {
                templateUrl: 'User/Facility',
                controller: 'FacilityController'
            })
        .otherwise(
            {
            redirectTo: 'User/UserDetail'
            });

    $locationProvider.html5Mode(true).hashPrefix('!');
}]);

My Controller.js looks like this:

/// <reference path="../scripts/angular.js" />
/// <reference path="module.js" />

app.controller("LoginController", function ($scope, $http) {
    alert("Login Controller Called");
}); 
app.controller("ProfileController",  function ($scope, $http) {
    alert("profile Controller Called");
});

app.controller("FacilityController",  function ($scope, $http) {
    alert("Facility controller called");
});

Index.cshtml looks like this

<div>
    <h1>header</h1>
</div>

<div class="main container" ng-view>
    <div>
        <a href="#/Login">Login</a>
        <a href="#/Profile">Profile</a>
        <a href="#/Facility">Facility</a>
    </div>

</div>

<footer class="footer py-4 bg-dark text-light">
    <h1>Footer</h1>
</footer>

Output is as follows:

[enter image description here](https://i.sstatic.net/NQfcL.png)

Login, profile and facility partial views are not loading.


Solution

  • In AngularJS version 1.6 they changed the hash-prefix for URL hash-bang. Links now have #! instead of #.

    so try with this

    <div>
      <a href="#!Login">Login</a>
      <a href="#!Profile">Profile</a>
      <a href="#!Facility">Facility</a>
    </div>
    

    Or if you want to remove the hash-prefix (!), you would need your config to have this code:

    $locationProvider.hashPrefix('');
    

    More about it: commit-aa077e8