Angularjs routing asp.net mvc example

In this article I try to make a simple example about how to apply angularjs routing for asp.net mvc application. After this you can know how to use angularjs routing and angularjs routing for MVC. Beside that you can know how to rout with parameter, how to use ng-view.
agenda:
  • Add MVC application
  • Reference angularjs to MVC application
  • Add angularjs router and angularjs controller
  • Modify _Layout.cshtml and some mvc view to use angularjs.
  • Run and see result


Add MVC application

Step 1:
From your visual studio File=> New project => Visual c# => ASP.Net Web Application=> input AngularJs_MVC_Routing to “Name:” => OK

=>  Choose MVC and then OK
Step 2:
-  Add AngularTemplates folder to root of project, this folder will be contains angularjs template of views
Add AngularJsRouting and AngularJsControllers folder to Scripts folder, this folders will be contains of angularjs routing and angularjs controllers

Your project structure look like as below:


 

Reference  angularjs library to MVC application

In this step add want to add angular.min.js and angular-route to my mvc application.
I dot it by add following code to header of View/Shared/_Layout.cshtml

   <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>  
   <script src="https://code.angularjs.org/1.4.7/angular-route.js"></script>  

Add angularjs router and angularjs controller

Step 1: add angularjs routing 
Right click Scripts\AngularJsRouting folder add Routing.js will following code:

 var app = angular.module('MyApp', ['ngRoute']);  
 app.config([  
   '$locationProvider', '$routeProvider',  
   function ($locationProvider, $routeProvider) {  
     $locationProvider.html5Mode({  
       enabled: true,  
       requireBase: false  
     }).hashPrefix('!');  
     $routeProvider  
     .when('/', { // For Home Page  
       templateUrl: '/AngularTemplates/Home.html',  
       controller: 'HomeController'  
      })  
     .when('/Home/Contact', { // For Contact page  
       templateUrl: '/AngularTemplates/Contact.html',  
       controller: 'ContactController'  
     })  
     .when('/Home/About', { // For About page  
       templateUrl: '/AngularTemplates/About.html',  
       controller: 'AboutController'  
     })  
     .when('/Home/User/:userid', { // For User page   
       templateUrl: '/AngularTemplates/User.html',  
       controller: 'UserController'  
     })  
     .otherwise({  // This is when any route not matched => error  
       controller: 'ErrorController'  
     })  
   }]);  

Description: above code I use $routeProvider to make rounting for 4 views (Home, Contact, About, User), note that I use templateUrl for each routing, we will add that templates later. Next step we must create angularjs controllers for each.

Step 1: add angularjs controllers
Based on routing code above we must add HomeController, ContactController, AboutController, UserController and ErrorController.

Right click Scripts\AngularJsControllers folder add Controllers.js will following code: 

 var app = angular.module('MyApp');  
 app.controller('UserController', ['$scope', '$routeParams', function ($scope, $routeParams) {  
   $scope.Message = "This is User Page with query string id value = " + $routeParams.userid;  
 }]);  
 app.controller('HomeController', function ($scope) {  
   $scope.Message = "This is HOME page";  
 })  
 app.controller('AboutController', function ($scope) {  
   $scope.Message = "This is ABOUT page";  
 })  
 app.controller('ContactController', function ($scope) {  
   // $routeParams used for get query string value  
   $scope.Message = "This is Contact Page ";  
 })  
 app.controller('ErrorController', function ($scope) {  
   $scope.Message = "404 Not Found!";  
 });  

Modify _Layout.cshtml and some mvc view to use angularjs.

- Step 1: Add templates for Home, About, User and Contact

Right click AngularTemplates add
+ About.html as following
 <h2>About Page</h2>  
 <p>{{Message}}</p>   

+ Contact.html as following
 <h2>Contact Page</h2>  
 <p>{{Message}}</p>   
+ Home.html as following
 <h2>Home Page</h2>  
 <p>{{Message}}</p>   
+ User.html as following
 <h2>User Page</h2>  
 <p>{{Message}}</p>   
 
- Step 2: open HomeController.cs add controller for User by following code

  public ActionResult User(int id)  
     {  
       ViewBag.Message = "Your user page.";  
       return View();  
     }  


Right click User controller method to add User view for it

- Step 3: open View/Shared/_Layout.cshtml and modify it by add Routing.js and Controllers.js and actionlink for User view


 <!DOCTYPE html>  
 <html>  
 <head>  
   <meta charset="utf-8" />  
   <meta name="viewport" content="width=device-width, initial-scale=1.0">  
   <title>@ViewBag.Title - My ASP.NET Application</title>  
   @Styles.Render("~/Content/css")  
   @Scripts.Render("~/bundles/modernizr")  
   <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>  
   <script src="https://code.angularjs.org/1.4.7/angular-route.js"></script>  
 </head>  
 <body ng-app="MyApp">  
   <div class="navbar navbar-inverse navbar-fixed-top">  
     <div class="container">  
       <div class="navbar-header">  
         <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">  
           <span class="icon-bar"></span>  
           <span class="icon-bar"></span>  
           <span class="icon-bar"></span>  
         </button>  
         @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })  
       </div>  
       <div class="navbar-collapse collapse">  
         <ul class="nav navbar-nav">  
           <li>@Html.ActionLink("Home", "Index", "Home")</li>  
           <li>@Html.ActionLink("About", "About", "Home")</li>  
           <li>@Html.ActionLink("Contact", "Contact", "Home")</li>  
           <li>@Html.ActionLink("User", "User/100", "Home")</li>  
         </ul>  
         @Html.Partial("_LoginPartial")  
       </div>  
     </div>  
   </div>  
   <div class="container body-content">  
     @RenderBody()  
     <hr />  
     <footer>  
       <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>  
     </footer>  
   </div>  
   @Scripts.Render("~/bundles/jquery")  
   @Scripts.Render("~/bundles/bootstrap")  
   @RenderSection("scripts", required: false)  
   <script src="~/Scripts/AngularJsRouting/Routing.js"></script>  
   <script src="~/Scripts/AngularJsControllers/Controllers.js"></script>  
 </body>  
 </html>  

Run and see result

 

 

Download AngularJs MVC Routing source code at GitHub.



Thanks for your time reading!



34 comments:

  1. Among many key features of AngularJS, routing is the technique using which we can design Single Page Application. Generally 2 things comes under this technique ng-view & ng-routing. ng-view act like a container where using routing we can load multiple templates. To make your journey easier here I am presenting more about routing with required examples http://jharaphula.com/example-of-using-angularjs-routing

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. I didn't understand where angularjs routing came in picture in above example. you are always using MVC routing using action links...

    ReplyDelete
  4. THIS IS HAS NOTHING TO DO WITH API

    ReplyDelete
  5. We are Number 1 in Accounting Assignment Help - Accounting Homework Help. Hire us for Accounting Term Papers and Accounting Projects.

    ReplyDelete
  6. Our website is number 1 in ASP Assignment Help and ASP.net Homework Help. This is preferred destination for various students to get their ASP Projects and Homework Done. ASPHelpOnline.com is easily the number 1 destination to get ASP help.

    ReplyDelete
  7. Our website is No. 1 in SolidWorks Project Help. Hire us for your SolidWorks Homework and Solidworks Assignment Help.

    ReplyDelete
  8. SPSSHelpOnline.com is number 1 website in SPSS assignment online help niche. This is desired place for many students to get their SPSS Homework, Projects & Assignments help taken from. We also provide Tutors for SPSS also. SPSS Assignment Help

    ReplyDelete
  9. We are No. 1 in Electronics Engineering Assignment Help; Hire us for your Electronics Engineering Project and Homework Help.

    ReplyDelete
  10. where are the cshtml views from ASP.NET MVC ?

    ReplyDelete
  11. I have read your blog its very attractive and impressive. I like it your blog.

    Angularjs Online Training Angularjs Training Angularjs Training Angularjs Training in Chennai Angularjs Training in Chennai Angularjs Course Angularjs Course Angular 2 Training in Chennai

    ReplyDelete
  12. I am writing a small program that will monitor the temperature, relative humidity, and the composition of gasses in a controlled environment. I am very grateful for the outstanding programming information provided on this website since it has helped me to debug my program accurately and I will only be seeking professional Research Paper Paraphrasing Help.

    ReplyDelete
  13. 9643950605 Croma Campus is one of the best Angularjs Training in Noida with 100% situation ensures. Croma Campus has very much characterized course modules and instructional meetings for understudies and Weekend classes, evening clump classes with live venture by industry master In Noida.

    ReplyDelete
  14. Angular JS has been enabling the web developers to come up with very interactive and unique websites. In fact, as more functionalities continue to be added, there is more and more interactivity in the developed websites. This blog has proven to be really helpful and I am glad that I have seen it. Learn on How to Get a Cheap Assignment Formatting Service from the experts and improve the quality of your programming assignments.

    ReplyDelete
  15. Thank you for your guide to with upgrade information.
    .Net Online Training bagnalore

    ReplyDelete
  16. This comment has been removed by the author.

    ReplyDelete
  17. Thanks for good information.To get information about MSBI training click here
    msbi training institutes in hyderabad

    ReplyDelete
  18. Thanks for sharing this Informative content. Well explained.
    AngularJs Training in Noida

    ReplyDelete
  19. Thank you for your informative article, I have been doing research on this subject, and for three days I keep entering sites that are supposed to have what I am searching for, only to be discouraged with the lack of what I needed. Thank you again.
    Data Science Training in Hyderabad
    Hadoop Training in Hyderabad
    selenium Online Training in Hyderabad
    Devops Online Training in Hyderabad
    Informatica Online Training in Hyderabad
    Tableau Online Training in Hyderabad

    ReplyDelete
  20. justquestionanswer.com provides the best homework help service to the students. Our expert team is available anytime to help in all academic writings like Dissertation Writing, Essay Writing Help, course work, Assignment Help.

    ReplyDelete
  21. Nice post! Thanks for sharing this information. Looking for help with your selecting your thesis topic? Get reliable research topics help from the leading Research Projects Writing Company at an affordable cost. Our experts are available 24/7.

    ReplyDelete
  22. Well written! You have covered many points. Please keep it up and keep us updated with the latest information. Thanks a lot!
    By Cognex
    AWS Training in Chennai

    ReplyDelete
  23. Superb. I really enjoyed very much with this article here. Really it is an amazing article I had ever read. I hope it will help a lot for all. Thank you so much for this amazing posts and please keep update like this excellent article.thank you for sharing such a great blog with us. expecting for your..
    By Cloudi5 web design and web development company in Coimbatore. Cloudi5 services are website creation, web design, e-commerce web design, digital marketing, SEO, SMM, landing page optimization, email marketing, etc

    ReplyDelete
  24. I just loved your article on the beginners guide to starting a blog.If somebody take this blog article seriously in their life, he/she can earn his living by doing blogging.Thank you for this article.
    blueprism online training

    ReplyDelete
  25. I am genuinely thankful to the holder of this web page who has shared this wonderful paragraph at this place

    Click Now
    Click Now
    Click Now
    Click Now
    Click Now
    Click Now
    Click Now
    Click Now
    Click Now
    Click Now

    ReplyDelete
  26. It’s a Very Good Blog. The Information in This Blog is Very Helpful. Thank You For Sharing Such Useful Content.
    Mechanics in Geelong
    Car Mechanics in Geelong

    ReplyDelete
  27. Buy Pink Lady 100mg utilizes the force of Buy Female Sildenafil 100mg to increment the bloodstream inside the body. The whole female conceptive system will get more blood and oxygen.
    For More Info Visit Link : https://bit.ly/3tknjbO

    ReplyDelete
  28. Your suggestions for improvement are spot-on. They would definitely enhance the website's functionality. Looking to improve your language skills? Study in Canada and immerse yourself in English or French.

    ReplyDelete
  29. This comment has been removed by the author.

    ReplyDelete

Popular Posts