Part 9 - How to implement AngularJS Routing in ASP.NET MVC application



Introduction

In the previous article of this series AngularJS With ASP.NET MVC I have explained how to upload files with AngularJS and ASP.NET MVC application. Today I am going to explain (Part 9) how to implement AngularJS Routing in ASP.NET MVC application.

Routing in AngularJS similar with MVC routing but MVC routing is server side and AngularJS routing is client side routing.

AngularJS routing operates in three modes:

  • Hashbang Mode (url like : "http://www.dotnetawesome.com/#!/dashboard")
  • HTML5 Mode (url like : " http://dotnetawesome.com/dashboard")
  • Hashbang in HTML5 Mode (url like : "http://www.dotnetawesome.com/#!/dashboard")
Here In this example I am going to use Hashbang Mode as I am using MVC as Server side.
HTML5 Mode url is more readable But there is following impact on the Server Side.
Suppose My domain is http://dotnetawesome.com, and I want to visit dashboard page. In the Hashbang Mode the url will looks like http://dotnetawesome.com/#!/dashboard. Now, if anyone type this url http://dotnetawesome.com/#!/dashboard in the address bar and hit enter then sever will response for http://dotnetawesome.com/ and after the #! was left for the client framework to interpret. But In the HTML5 Mode the url will looks like http://dotnetawesome.com/dashboard this means that if you don’t have a handler for the URL /dashboard then your application will break. This problem will not arise when you are clicking links in your website, since you have already loaded AngularJS by that point. AngularJS will see the /dashboard and handle it on the client side.

Now we are going to implement AngularJS routing. Please follow the below steps...

Steps :

Step-1: Create a Folder for Store our views/templates (HTML files).

Go to solution explorar > Right Click on the Project > Add > New Folder > Enter Folder Name.
In this example, I have created a folder "Template".

Step-2: Add views/templates (HTML files).

Go to Solution Explorer > Right Click On the folder (here Template)> Add > New Item... > Select HTML Page (under Web) > Enter Name > Add.
In this example I have added the following 4 views/templates...
  • Home.html
  • About.html
  • Order.html
  • Error.html

Home.html

<div ng-controller="HomeController">
    <h2>Home Page</h2>
    <h5>{{Message}}</h5>
</div>
        

About.html

<div ng-controller="AboutController">
    <h2>About Page</h2>
    <h5>{{Message}}</h5>
</div>
        

Order.html

<div ng-controller="OrderController">
    <h2>Order Page</h2>
    <h5>{{Message}}</h5>
</div>
        

Error.html

<div ng-controller="ErrorController">
    <h2>Error Page</h2>
    <h5>{{Message}}</h5>
</div>
        

Step-3: Add a new js File for configure AngularJS routing and add controllers

Go to Solution Explorer > Right Click on folder (where you want to saved your AngularJS controller files, here I have created a folder named "AngularController"  under Scripts Folder) > Add > Select Javascript file > Enter name > Add.

Write following code in this file (here Routing.js).
angular.module('MyApp', ['ngRoute']) //extending from previously created angularjs module in part1
// here ['ngRoute'] is not required, I have just added to make you understand in a single place
.config(function ($routeProvider, $locationProvider) {
    //here we will write code for implement routing 
    $routeProvider
    .when('/', { // This is for reditect to another route
        redirectTo: function () {
            return '/home';
        }
    })
    .when('/home', {
        templateUrl: '/Template/Home.html',
        controller: 'HomeController'
    })
    .when('/about', {
        templateUrl: '/Template/About.html',
        controller: 'AboutController'
    })
    .when('/order/:id', {
        templateUrl: '/Template/Order.html',
        controller: 'OrderController'
    })
    .otherwise({   // This is when any route not matched
        templateUrl: '/Template/Error.html',
        controller: 'ErrorController'
    })

    $locationProvider.html5Mode(false).hashPrefix('!'); // This is for Hashbang Mode
})
.controller('HomeController', function ($scope) {
    $scope.Message = "This is HOME page";
})
.controller('AboutController', function ($scope) {
    $scope.Message = "This is ABOUT page";
})
.controller('OrderController', function ($scope, $routeParams) {
    // $routeParams used for get query string value
    $scope.Message = "This is ORDER Page with query string id value " + $routeParams.id;
})
.controller('ErrorController', function ($scope) {
    $scope.Message = "404 Not Found!";
});

        
You can see here I have used the followings...
  • $routeProvider: is taken care of Routing , which is the provider of the $route service.
  • $locationProvider: use to configure how the application deep linking paths are stored.
  • $routeParams: is used for get query string value.

Step-4: Add new action into your controller (here in the HomeController) for Get the view for Implement routing.

Here I have added "Part9" Action into "Home" Controller. Please write this following code

public ActionResult Part9() // Upload File with Data
{
    return View();
}
        

Step-5: Add view for the Action & design.

Right Click on Action Method (here right click on Part9 action) > Add View... > Enter View Name > Select View Engine (Razor) > Add.
Here you can see I have used <ng-view></ng-view> which
Complete View
@{
    ViewBag.Title = "Part9";
}
<style>
    ul.menu {
        list-style:none;
        padding:10px;
        margin:0px;
    }
        ul.menu li {
            float:left;
            margin:1px;
        }
        ul.menu li a{
            float:left;
            background-color:#f3f3f3;
            display:inline-block;
            padding:5px 20px;
            
        }
            ul.menu li a:hover {
                background-color:#e4e4e4;
            }
</style>

<h2>Part9 - Routing in angularJs</h2>
<div>
    <ul class="menu">
        <li><a href="#!/home">Home</a></li>
        <li><a href="#!/about">About</a></li>
        <li><a href="#!/order/100">Order</a></li>
        <li><a href="#!/invalid">Invalid Url</a></li>
    </ul>
</div>
<div style="padding:0 10px; margin:10px; border:10px solid #f3f3f3; clear:both;">
    <ng-view></ng-view>
</div>
@section Scripts{
    <script src="~/Scripts/AngularController/Routing.js"></script>
}
          
        

Step-6: Run Application.




Hello ! My name is Sourav Mondal. I am a software developer working in Microsoft .NET technologies since 2010.

I like to share my working experience, research and knowledge through my site.

I love developing applications in Microsoft Technologies including Asp.Net webforms, mvc, winforms, c#.net, sql server, entity framework, Ajax, Jquery, web api, web service and more.