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
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- namespace MVCWithAngularJs.Controllers
- {
- public class HomeController : Controller
- {
- //
- // GET: /Home/
- public ActionResult Index()
- {
- return View();
- }
- public ActionResult Routing() // Routing
- {
- return View();
- }
- }
- }
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
- @{
- ViewBag.Title = "Index";
- }
- <h2>Index</h2>
- <div ng-controller="HomeController">
- {{Message}}
- </div>
The above message will be fetched from Myapp.JS file.
- (function () {
- var app = angular.module('MyApp', ['ngRoute']);
- app.controller('HomeController', function ($scope) {
- $scope.Message = "My Name Is Satyaprakash Samantaray.";
- });
- })();
- var app = angular.module('MyApp', ['ngRoute']);
- app.controller('HomeController', function ($scope) {
- app.controller('HomeController', function ($scope) {
- $scope.Message = "My Name Is Satyaprakash Samantaray.";
- });
Step 3
Then, we have added some code snippet in Routing.cshtml file.
Code Ref
- @{
- ViewBag.Title = "Routing";
- }
- <h2>AngularJS Routing</h2>
- <style>
- ul {
- list-style-type: none;
- margin: 0;
- padding: 0;
- overflow: hidden;
- background-color: #333;
- }
- li {
- float: left;
- border-right:1px solid #bbb;
- }
- li:last-child {
- border-right: none;
- }
- li a {
- display: block;
- color: white;
- text-align: center;
- padding: 14px 16px;
- text-decoration: none;
- }
- li a:hover:not(.active) {
- background-color: #111;
- }
- .active {
- background-color: #4CAF50;
- }
- </style>
- <div>
- <ul>
- <li><a class="active" href="#!/home">Profile</a></li>
- <li><a href="#!/Article">Article</a></li>
- <li><a href="#!/Blog/098Xfs1234">Blog</a></li>
- <li><a href="#!/Page-Not-Found">Error</a></li>
- </ul>
- </div>
- <div style="padding:14px 16px; margin:10px; border:10px solid Blue; clear:both;">
- <ng-view></ng-view>
- </div>
- @section Scripts{
- <script src="~/Scripts/AngularController/Routing.js"></script>
- }
This cshtml file totally depends upon the file called "Routing.JS". Here, I have mentioned the file path reference.
- @section Scripts{
- <script src="~/Scripts/AngularController/Routing.js"></script>
- }
Code for Routing.JS
- angular.module('MyApp', ['ngRoute'])
- .config(function ($routeProvider, $locationProvider) {
- $routeProvider
- .when('/', {
- redirectTo: function () {
- return '/home';
- }
- })
- .when('/home', {
- templateUrl: '/Template/Profile.html',
- controller: 'HomeController'
- })
- .when('/Article', {
- templateUrl: '/Template/Article.html',
- controller: 'ArticleController'
- })
- .when('/Blog/:id', {
- templateUrl: '/Template/Blog.html',
- controller: 'BlogController'
- })
- .otherwise({
- templateUrl: '/Template/Error.html',
- controller: 'ErrorController'
- })
- $locationProvider.html5Mode(false).hashPrefix('!');
- })
- .controller('HomeController', function ($scope) {
- $scope.Message = "http://www.c-sharpcorner.com/members/satyaprakash-samantaray";
- })
- .controller('ArticleController', function ($scope) {
- $scope.Message = "http://www.c-sharpcorner.com/article/introduction-to-sql-operations-studio-and-make/";
- })
- .controller('BlogController', function ($scope, $routeParams) {
- $scope.Message = "http://www.c-sharpcorner.com/blogs/career-booster-through-c-sharp-corner" + "Of Id" + $routeParams.id;
- })
- .controller('ErrorController', function ($scope) {
- $scope.Message = "Page You Requested Not Found!";
- });
- $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.
- angular.module('MyApp', ['ngRoute'])
- .config(function ($routeProvider, $locationProvider) {
- $routeProvider
- $routeProvider
- .when('/', {
- redirectTo: function () {
- return '/home';
- }
- })
- .when('/home', {
- templateUrl: '/Template/Profile.html',
- controller: 'HomeController'
- })
- .when('/Article', {
- templateUrl: '/Template/Article.html',
- controller: 'ArticleController'
- })
- .when('/Blog/:id', {
- templateUrl: '/Template/Blog.html',
- controller: 'BlogController'
- })
- .otherwise({
- templateUrl: '/Template/Error.html',
- controller: 'ErrorController'
- })
- .otherwise({
- templateUrl: '/Template/Error.html',
- controller: 'ErrorController'
- })
- $locationProvider.html5Mode(false).hashPrefix('!');
- .controller('HomeController', function ($scope) {
- $scope.Message = "http://www.c-sharpcorner.com/members/satyaprakash-samantaray";
- })
- .controller('ArticleController', function ($scope) {
- $scope.Message = "http://www.c-sharpcorner.com/article/introduction-to-sql-operations-studio-and-make/";
- })
- .controller('BlogController', function ($scope, $routeParams) {
- $scope.Message = "http://www.c-sharpcorner.com/blogs/career-booster-through-c-sharp-corner" + "Of Id" + $routeParams.id;
- })
- .controller('ErrorController', function ($scope) {
- $scope.Message = "Page You Requested Not Found!";
- });
- .controller('BlogController', function ($scope, $routeParams) {
- $scope.Message = "http://www.c-sharpcorner.com/blogs/career-booster-through-c-sharp-corner" + "Of Id" + $routeParams.id;
- })
Step 4
Then we should add 4 HTML files inside Template folder and assign some code.
Code Reference
For Article.html file.
- <div ng-controller="ArticleController">
- <h2>My Article Url</h2>
- <h5>{{Message}}</h5>
- </div>
- <div ng-controller="BlogController">
- <h2>My Blog Url</h2>
- <h5>{{Message}}</h5>
- </div>
- <div ng-controller="HomeController">
- <h2>My Profile Url</h2>
- <h5>{{Message}}</h5>
- </div>
- <div ng-controller="ErrorController">
- <h2>Page Under Construction....</h2>
- <h5>{{Message}}</h5>
- </div>
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 -
- <li><a class="active" href="#!/home">Profile</a></li>
- <li><a href="#!/Article">Article</a></li>
- <li><a href="#!/Blog/098Xfs1234">Blog</a></li>
- <li><a href="#!/Page-Not-Found">Error</a></li>
/..../#!/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,
- public static void RegisterRoutes(RouteCollection routes)
- {
- routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
- routes.MapRoute(
- name: "Default",
- url: "{controller}/{action}/{id}",
- defaults: new { controller = "Home", action = "Routing", id = UrlParameter.Optional }
- );
- }
- }
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
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width" />
- <title>@ViewBag.Title</title>
- @Styles.Render("~/Content/css")
- @Scripts.Render("~/bundles/modernizr")
- @*<style>
- /*.menuUl {
- list-style:none;
- margin:0px;
- padding:0px;
- }
- .menuUl li {
- float:left;
- padding:3px;
- margin-right:2px;
- background-color:#f3f3f3;
- }
- .menuUl li a {
- display:block;
- line-height:30px;
- padding:0px 5px;
- color:#920f0f;
- text-decoration:none;
- }
- .menuUl li a:hover {
- text-decoration:underline;
- }*/
- </style>*@
- </head>
- @* Here ng-app="MyApp" is used for auto-bootstrap an AngularJS application. here ng-app="MyApp" means <body> element is the owner
- of AngularJS application*@
- <body ng-app="MyApp">
- @*<ul class="menuUl">
- <li>@Html.ActionLink("Go To Menu>>", "Routing")</li>
- </ul>*@
- <div style="height:1px; clear:both;"></div>
- @RenderBody()
- @Scripts.Render("~/bundles/jquery")
- @* Add Angular Library Here *@
- @Scripts.Render("~/bundles/angular")
- <script src="~/Scripts/MyApp.js"></script>
- @RenderSection("scripts", required: false)
- </body>
- </html>
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.
of AngularJS application. Also, I have added an Angular Library here.
- <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.

Cristo FerraoPosted Jul 21, 2021, 10:05 AM
Can you upload the project to github
Tridip BhattacharjeePosted Apr 6, 2018, 6:51 AM
Can't we remove #! from url but routing should work?
Tridip BhattacharjeePosted Apr 6, 2018, 4:00 AM
Good article but i do not understand why this character is in url #! ? please tell me what is the importance of this character #! in url? if i do not give this char #! in url then what will happen? looking for answer. thanks