In Focus

Client Side Routing Using Angular In MVC

AngularJS supports a Single page application routing module called ngRoute. When a user requests a specific url, the routing engine fetches that url and renders the view based on the defined routing rules. AngularJS appends '/#/' to the url to redirect to a particular url using $location service. For example, to redirect to '/Article', the url would be http://localhost/#/Article.

Introduction
 
AngularJS supports Single Page Application routing module called ngRoute. When a user requests a specific URL, the routing engine fetches that URL and renders the View based on the defined routing rules. AngularJS appends '/#/' to the URL to redirect to a particular URL using $location service. For example, to redirect to '/Article', the URL would be http://localhost/#/Article.
 
Description
 
In this Module, I will show you how to implement routing using AngularJS and create some menu. After clicking the menu link, the URL site address will be changed as we have configured in AnguarJS.
 
Download the Source Code
 
 
Difference between MVC Routing and AngularJS Routing
 
ASP.NET MVC is a server-side page rendering framework. AngularJS is a client-side page rendering framework. Routing in AngularJS is similar to MVC routing but MVC routing is server-side while the AngularJS routing is client-side routing.
 
Steps to be followed
 
Step 1
 
I have added some code to HomeController section.
 
Code Reference
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6.   
  7. namespace MVCWithAngularJs.Controllers  
  8. {  
  9.     public class HomeController : Controller  
  10.     {  
  11.         //  
  12.         // GET: /Home/          
  13.         public ActionResult Index()  
  14.         {  
  15.             return View();  
  16.         }  
  17.   
  18.         public ActionResult Routing() // Routing  
  19.         {  
  20.             return View();  
  21.         }  
  22.   
  23.     }  

Code Description
 
Here, the Index Controller action method to show a normal message and Routing Controller action method for AngularJS routing related output.
 
Step 2
 
Then, add some code snippet in Index View cshtml file.
 
Code Reference
  1. @{  
  2.     ViewBag.Title = "Index";  
  3. }  
  4.   
  5. <h2>Index</h2>  
  6. <div ng-controller="HomeController">  
  7.     {{Message}}     
  8. </div> 
Description
 
The above message will be fetched from Myapp.JS file.
  1. (function () {  
  2.     var app = angular.module('MyApp', ['ngRoute']);  
  3.     app.controller('HomeController'function ($scope) {  
  4.         $scope.Message = "My Name Is Satyaprakash Samantaray.";  
  5.     });  
  6. })(); 
Here, I have created a module.
  1. var app = angular.module('MyApp', ['ngRoute']);  
Here, I have used ['ng-Route'] when we will implement routing. Then, created a Controller.
  1. app.controller('HomeController'function ($scope) { 
Here, $scope is used for sharing the data between View and Controller.
  1. app.controller('HomeController'function ($scope) {   
  2.         $scope.Message = "My Name Is Satyaprakash Samantaray.";  
  3.     });  
Step 3
 
Then, we have added some code snippet in Routing.cshtml file. 
 
Code Ref
  1. @{  
  2.     ViewBag.Title = "Routing";  
  3. }  
  4.   
  5. <h2>AngularJS Routing</h2>  
  6.   
  7. <style>  
  8.    ul {  
  9.     list-style-type: none;  
  10.     margin: 0;  
  11.     padding: 0;  
  12.     overflow: hidden;  
  13.     background-color: #333;  
  14. }  
  15.   
  16. li {  
  17.     float: left;  
  18.     border-right:1px solid #bbb;  
  19. }  
  20.   
  21. li:last-child {  
  22.     border-right: none;  
  23. }  
  24.   
  25. li a {  
  26.     display: block;  
  27.     color: white;  
  28.     text-align: center;  
  29.     padding: 14px 16px;  
  30.     text-decoration: none;  
  31. }  
  32.   
  33. li a:hover:not(.active) {  
  34.     background-color: #111;  
  35. }  
  36.   
  37. .active {  
  38.     background-color: #4CAF50;  
  39. }  
  40. </style>  
  41. <div>  
  42.     <ul>  
  43.         <li><a class="active" href="#!/home">Profile</a></li>  
  44.         <li><a href="#!/Article">Article</a></li>  
  45.         <li><a href="#!/Blog/098Xfs1234">Blog</a></li>  
  46.         <li><a href="#!/Page-Not-Found">Error</a></li>  
  47.     </ul>  
  48. </div>  
  49. <div style="padding:14px 16px; margin:10px; border:10px solid Blue; clear:both;">  
  50.     <ng-view></ng-view>  
  51. </div>  
  52. @section Scripts{  
  53.     <script src="~/Scripts/AngularController/Routing.js"></script>  

Code Desc
 
This cshtml file totally depends upon the file called "Routing.JS". Here, I have mentioned the file path reference.
  1. @section Scripts{  
  2.     <script src="~/Scripts/AngularController/Routing.js"></script>  
  3. }  
Code for Routing.JS
  1. angular.module('MyApp', ['ngRoute'])  
  2. .config(function ($routeProvider, $locationProvider) {  
  3.     $routeProvider  
  4.     .when('/', {  
  5.         redirectTo: function () {  
  6.             return '/home';  
  7.         }  
  8.     })  
  9.     .when('/home', {  
  10.         templateUrl: '/Template/Profile.html',  
  11.         controller: 'HomeController'  
  12.     })  
  13.     .when('/Article', {  
  14.         templateUrl: '/Template/Article.html',  
  15.         controller: 'ArticleController'  
  16.     })  
  17.     .when('/Blog/:id', {  
  18.         templateUrl: '/Template/Blog.html',  
  19.         controller: 'BlogController'  
  20.     })  
  21.     .otherwise({     
  22.         templateUrl: '/Template/Error.html',  
  23.         controller: 'ErrorController'  
  24.     })  
  25.   
  26.     $locationProvider.html5Mode(false).hashPrefix('!');   
  27. })  
  28. .controller('HomeController'function ($scope) {  
  29.     $scope.Message = "http://www.c-sharpcorner.com/members/satyaprakash-samantaray";  
  30. })  
  31. .controller('ArticleController'function ($scope) {  
  32.     $scope.Message = "http://www.c-sharpcorner.com/article/introduction-to-sql-operations-studio-and-make/";  
  33. })  
  34. .controller('BlogController'function ($scope, $routeParams) {  
  35.     $scope.Message = "http://www.c-sharpcorner.com/blogs/career-booster-through-c-sharp-corner" + "Of Id"  + $routeParams.id;  
  36. })  
  37. .controller('ErrorController'function ($scope) {  
  38.     $scope.Message = "Page You Requested Not Found!";  
  39. }); 
  • $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.
['ngRoute'] is added to make you understand in a single place.
  1. angular.module('MyApp', ['ngRoute']) 
Here, we will write the code for implementing the routing.
  1. .config(function ($routeProvider, $locationProvider) {  
  2.       
  3.     $routeProvider 
This is for redirecting to another route.
  1. $routeProvider  
  2.     .when('/', {  
  3.         redirectTo: function () {  
  4.             return '/home';  
  5.         }  
  6.     }) 
Here, 4 different routes are mentioned. After clicking on the HTML file, the mentioned path will show the page output with URL routing.
  1. .when('/home', {  
  2.         templateUrl: '/Template/Profile.html',  
  3.         controller: 'HomeController'  
  4.     })  
  5.     .when('/Article', {  
  6.         templateUrl: '/Template/Article.html',  
  7.         controller: 'ArticleController'  
  8.     })  
  9.     .when('/Blog/:id', {  
  10.         templateUrl: '/Template/Blog.html',  
  11.         controller: 'BlogController'  
  12.     })  
  13.     .otherwise({
  14.         templateUrl: '/Template/Error.html',  
  15.         controller: 'ErrorController'  
  16.     }) 
If any Route does not matche, it will redirect the ueser here.
  1. .otherwise({     
  2.        templateUrl: '/Template/Error.html',  
  3.        controller: 'ErrorController'  
  4.    }) 
Here, I have used Hashbang Mode.
  1. $locationProvider.html5Mode(false).hashPrefix('!'); 
Then, I used $scope to show the route related output.
  1. .controller('HomeController'function ($scope) {  
  2.     $scope.Message = "http://www.c-sharpcorner.com/members/satyaprakash-samantaray";  
  3. })  
  4. .controller('ArticleController'function ($scope) {  
  5.     $scope.Message = "http://www.c-sharpcorner.com/article/introduction-to-sql-operations-studio-and-make/";  
  6. })  
  7. .controller('BlogController'function ($scope, $routeParams) {  
  8.     $scope.Message = "http://www.c-sharpcorner.com/blogs/career-booster-through-c-sharp-corner" + "Of Id"  + $routeParams.id;  
  9. })  
  10. .controller('ErrorController'function ($scope) {  
  11.     $scope.Message = "Page You Requested Not Found!";  
  12. }); 
Based on the Controller name, the AngularJS HTML files we have added will show the output. For example, for blog Controller, the output should be.
  1. .controller('BlogController'function ($scope, $routeParams) {    
  2.     $scope.Message = "http://www.c-sharpcorner.com/blogs/career-booster-through-c-sharp-corner" + "Of Id"  + $routeParams.id;    
  3. }) 
 $routeParams is used for getting the query string value.
 
Step 4
 
Then we should add 4 HTML files inside Template folder and assign some code.
 
Code Reference
 
For Article.html file.
  1. <div ng-controller="ArticleController">  
  2.     <h2>My Article Url</h2>  
  3.     <h5>{{Message}}</h5>  
  4. </div> 
For Blog.html File.
  1. <div ng-controller="BlogController">  
  2.     <h2>My Blog Url</h2>  
  3.     <h5>{{Message}}</h5>  
  4. </div> 
For Profile.html file.
  1. <div ng-controller="HomeController">  
  2.     <h2>My Profile Url</h2>  
  3.     <h5>{{Message}}</h5>  
  4. </div> 
For Error.html file.
  1. <div ng-controller="ErrorController">  
  2.     <h2>Page Under Construction....</h2>  
  3.     <h5>{{Message}}</h5>  
  4. </div> 
Code Desc
 
Each individual HTML file contains its corresponding Controller name given in the AngularJS file. In Error controller, I have defined a "page not found" logic that is 404. If any route is not found, then the "page not found page" will be shown.
 
In Step 3 Code, I have added some code -
  1. <li><a class="active" href="#!/home">Profile</a></li>  
  2.        <li><a href="#!/Article">Article</a></li>  
  3.        <li><a href="#!/Blog/098Xfs1234">Blog</a></li>  
  4.        <li><a href="#!/Page-Not-Found">Error</a></li> 
If I click on the above mentioned link, the mentioned route path will be shown. If I click on the article link, the route path will show like this.
/..../#!/Article.
 
Step 5
 
Then, I have defined the route path when the page will load for the first time.
 
Code Ref. for RouteConfig.cs file,
  1. public static void RegisterRoutes(RouteCollection routes)  
  2.         {  
  3.             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  4.   
  5.             routes.MapRoute(  
  6.                 name: "Default",  
  7.                 url: "{controller}/{action}/{id}",  
  8.                 defaults: new { controller = "Home", action = "Routing", id = UrlParameter.Optional }  
  9.             );  
  10.         } 
  11. }
Code Desc
 
Here, Home is the Controller name and Routing is the Controller action method or View name.
 
Step 6
 
Add the following code in "_Layout.cshtml"  file.
 
Code Ref
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <meta charset="utf-8" />  
  5.     <meta name="viewport" content="width=device-width" />  
  6.     <title>@ViewBag.Title</title>  
  7.     @Styles.Render("~/Content/css")  
  8.     @Scripts.Render("~/bundles/modernizr")  
  9.     @*<style>  
  10.         /*.menuUl { 
  11.             list-style:none; 
  12.             margin:0px; 
  13.             padding:0px; 
  14.         } 
  15.             .menuUl li { 
  16.                 float:left; 
  17.                 padding:3px; 
  18.                 margin-right:2px; 
  19.                 background-color:#f3f3f3; 
  20.             } 
  21.                 .menuUl li a { 
  22.                     display:block; 
  23.                     line-height:30px; 
  24.                     padding:0px 5px; 
  25.                     color:#920f0f; 
  26.                     text-decoration:none; 
  27.                 } 
  28.                     .menuUl li a:hover { 
  29.                         text-decoration:underline; 
  30.                     }*/  
  31.     </style>*@  
  32. </head>  
  33.     @* Here  ng-app="MyApp" is used for auto-bootstrap an AngularJS application. here ng-app="MyApp" means <body> element is the owner   
  34.     of AngularJS application*@  
  35.   
  36.   
  37. <body ng-app="MyApp">  
  38.      @*<ul class="menuUl">  
  39.          <li>@Html.ActionLink("Go To Menu>>""Routing")</li>  
  40.      </ul>*@  
  41.     <div style="height:1px; clear:both;"></div>  
  42.     @RenderBody()  
  43.   
  44.     @Scripts.Render("~/bundles/jquery")  
  45.     @* Add Angular Library Here *@  
  46.     @Scripts.Render("~/bundles/angular")  
  47.     <script src="~/Scripts/MyApp.js"></script>  
  48.     @RenderSection("scripts", required: false)  
  49. </body>  
  50. </html> 
Code Desc
 
Here, ng-app="MyApp" is used for auto-bootstrapping an AngularJS application. ng-app="MyApp" means <body> element is the owner
of AngularJS application. Also, I have added an Angular Library here.
  1. <script src="~/Scripts/MyApp.js"></script>   
Notes
 
Routing in AngularJS is similar to MVC routing but MVC routing is server-side and AngularJS routing is client-side routing.
  • Hashbang Mode >> (site like : "http://www.c-sharpcorner.com/#!/MyProfile")
  • HTML5 Mode >> (site like : " http://www.c-sharpcorner.com/MyProfile")
  • Hashbang in HTML5 Mode >> (site like : "http://www.c-sharpcorner.com/#!/MyProfile")
In Hashbang Mode, since the MVC is Server side, the HTML5 Mode URL is more readable but there is the following impact of the Server Side.
 
Suppose, the domain is www.c-sharpcorner.com, and I want to visit MyProfile page. In the Hashbang Mode, the URL will look like http://www.c-sharpcorner.com/#!/MyProfile. Now, if anyone types this URL http://www.c-sharpcorner.com/#!/MyProfile in the address bar and hits Enter, the Sever will respond for www.c-sharpcorner.com/ and the "#!" part is left for the client side framework to interpret.
 
But In the HTML5 Mode, the URL will look like http://www.c-sharpcorner.com/MyProfile; this means that if you don’t have a handler for the URL /MyProfile, then your page will be not found and an issue will be shown. This problem will not arise when you click on the links on your website since you have already loaded AngularJS by that point. AngularJS will see the /MyProfile and handle it on the client side.  
 
OUTPUT
 
For Index View
 

For Routing View
 
When the page will load the first time, the route name should be Home and the HomeController related output will be shown as below.
 

Bootstrap Support
 
 
 
GIF Images for better understanding
 

Summary

We have learned the following in this article.
  • Define Routing In AngularJS.
  • AngularJS Routing vs MVC Routing.
  • Build Sample Application using MVC to implement AngularJS Routing.