AngularJS with ASP.Net MVC

AngularJS with ASP.Net MVC (Part 6)

A step by step tutorial on how to use AngularJS with ASP.Net MVC

Precap

I have started this as a multi-post tutorial a few posts back. In the previous parts we have created a minimal project in Visual Studio 2015 using Web Application’s Empty template with MVC folders and references. The application is running now with the bootstrapped UI containing a navigation of 3 pages. You can read those posts part 1part 2part 3part 4 and part 5 in case you have not gone through that already. Let’s move to next step where we will be delegating the routing at client side using AngularJS.

Start Using AngularJS

During this post we will be creating an AngularJS module and tell our ASP.Net MVC application to use that. It will do client side routing while rendering the views from the MVC actions.

AngularJS Routing

We are required to add another library here, which we need for the AngularJS routing. Open the command prompt and execute the below command in the project root folder. This will install a new folder in the bower_components, which we need to include in the project.

bower install angular-route --save

Modify Bundles

Open BundleConfig.cs file and include the new JavaScript file in there for the js bundle as shown in the snippet below.

 "~/bower_components/angular/angular.js",
 "~/bower_components/angular-route/angular-route.js",
 "~/bower_components/angular-ui-router/release/angular-ui-router.js",

Define AngularJS Module (app)

Create a new file named app.module.js under Scripts -> app folder (we have to create folder named app in case that is not already there) and put below code in there.

(function () {
    'use strict';

    angular.module('app', ['ngRoute']);
})();

Module Configuration

Next step is to configure the routing for AngularJS. Create a new file named app.config.js under Scripts -> app folder and add the blow code to it.

(function () {
    'use strict';

    angular.module('app')
        .config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
            $locationProvider.hashPrefix('');
            $routeProvider
                .when('/', {
                    templateUrl: '/Home/Home'
                })
                .when('/Page1', {
                    templateUrl: '/Home/Page1'
                })
                .when('/Page2', {
                    templateUrl: '/Home/Page2'
                })
                .when('/Page3', {
                    templateUrl: '/Home/Page3'
                });
        }]);
})();

Once you are done creating these files, include them in your bundle by editing the BundleConfig.cs file as shown below.

"~/bower_components/angular-ui-router/release/angular-ui-router.js",
"~/bower_components/bootstrap/dist/js/bootstrap.js",
"~/Scripts/app/app.module.js",
"~/Scripts/app/app.config.js"

Include AngularJS module in HTML

We are ready with the AngularJS module and now we need to include the module in the _Layout.cshtml. To do so, please modify your _Layout.cshtml file as per the code snippet below.

<!DOCTYPE html>
<html ng-app="app">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My AngularJS App</title>
    @Styles.Render("~/css")
</head>
<body>
    <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
        <div class="container-fluid">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#main-nav">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="/">AngularJS with ASP.Net MVC</a>
            </div>
            <div class="collapse navbar-collapse" id="main-nav">
                <ul class="nav navbar-nav">
                    <li>
                        <a href="/#/Page1">Page 1</a>
                    </li>
                    <li>
                        <a href="/#/Page2">Page 2</a>
                    </li>
                    <li>
                        <a href="/#/Page3">Page 3</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>
    @RenderBody()
    @Scripts.Render(new string[] { "~/js" })
</body>
</html>

Replace the content of Index.cshtml as per the snippet below

<div ng-view></div>

Modify the HomeController.cs while adding a new Action method named Home. Please not that we are now returning PartialView() in place of View() from some of the Action Methods.

using System.Web.Mvc;

namespace AngularJSwithMVC.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Home()
        {
            return PartialView();
        }

        public ActionResult Page1()
        {
            return PartialView();
        }

        public ActionResult Page2()
        {
            return PartialView();
        }

        public ActionResult Page3()
        {
            return PartialView();
        }
    }
}
<!-- Home.cshtml -->
<h1>Home Page</h1>

The Output …

As you can see in the output, we are now seeing the application from the AngularJS prospective. Here all the links are ‘#’ hashed where on clicking the Page links, it is only changing the view rather than loading the complete page again.

This video shows the including of AngularJS in MVC
description: Series: AngularJs with ASP.Net MVC In this video we will be including angular on top of ASP.Net MVC application created during the previous video. references are taken from blog post series: https://www.mindzgrouptech.net/urpd
duration: 00:18:53
views: 591
by: MindzGroupTech
source: YouTube
Get this plugin here.

In case you have any questions till this point, you can always leave the comments and I will try to answer them as soon as possible. I will continue on the next part of this series and leave you here with your brain to play with the idea. In the next part you will see another way of doing the routing, by using ui-router, another AngularJS library most commonly used in large scale modular applications. Bye till then!

Series Links

Part 1 Part 2 Part 3 Part 4 Part 5 Part 7 Part 8 Part 9 Part 10 Part 11

4 thoughts on “AngularJS with ASP.Net MVC (Part 6)”

  1. Hi, at this Part6 im getting below error something to do with ngRoute,
    please help me

    Unhandled exception at line 3855, column 3 in http://localhost:58297/bower_components/jquery/dist/jquery.js

    0x800a139e – JavaScript runtime error: [$injector:modulerr] Failed to instantiate module app due to:

    Error: [$injector:modulerr] Failed to instantiate module ngRoute due to:

    Error: [$injector:nomod] Module ‘ngRoute’ is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

    http://errors.angularjs.org/1.6.2/$injector/nomod?p0=ngRoute

    1. I guess you are forgetting to include the file required in the bundle config. Can you please verify if the file is there in the bundle config or the path you have specified is correctly spelled. you can take help of the chrome developer consoles network tab to see, which all files are making its path till bowser. Please let me know in case you are still stuck up.

  2. I had the same problem. I had gotten the bundled files in the wrong order and the path to angular-route.js incorrect.

Leave a Reply