Full-Stack MVC Application Development with AngularJS

These days, developers are interested to use AngularJS and ASP.NET MVC (wiring MVC and AngularJS). So in this post we will learn how to combine the best of both worlds and use the goodness of AngularJS in ASP.NET MVC. 

To start, let’s create ASP.NET MVC application and right click on the MVC project. From the context menu, click on Manage Nuget Package. Search for the AngularJS package and install into the project.

After successfully adding the AnngularJS library, you can find those files inside the Scripts folders.

Reference of AngularJS library

You have two options to add an AngularJS library reference in the project: MVC minification and bundling or by adding AngularJS in the Script section of an individual view. If you use bundling, then AngularJS will be available in the whole project. However you have the option to use AngularJS on a particular view as well.

Let’s say you want to use AngularJS on a particular view (Index.cshtml) of the Home controller. First you need to refer to the AngularJS library inside the scripts section as shown below:

@section scripts{

    <script src=”~/Scripts/angular.js”>script>

}

Next, apply the ng-app directive and any other required directives on the HTML element as shown below:

<div ng-app=”” class=”row”>

     <input type=”text” ng-model=”name” />

     {{name}}

div>

When you run the application you will find AngularJS is up and running in the Index view. In this approach you will not be able to use AngularJS on the other views because the AngularJS library is only referenced in the Index view.

You may have a requirement to use AngularJS in the whole MVC application. In this case, it’s better to use bundling and minification of MVC and all the AngularJS libraries at the layout level. To do this, open BundleConfig.cs from the App_Start folder and add a bundle for the AngularJS library as shown below:

  public static void RegisterBundles(BundleCollection bundles)

        {

            bundles.Add(new ScriptBundle(“~/bundles/angular”).Include(

                        “~/Scripts/angular.js”));

 

After adding the bundle in the BundleConfig file, next you need to add the AngularJS bundle in the _Layout.cshtml as listed below:

<head>

    <meta charset=”utf-8″ />

    <meta name=”viewport” content=”width=device-width, initial-scale=1.0″>

    <title>@ViewBag.Title – My ASP.NET Applicationtitle>

    @Styles.Render(“~/Content/css”)

    @Scripts.Render(“~/bundles/modernizr”)

    @Scripts.Render(“~/bundles/angular”)

    @Scripts.Render(“~/bundles/jquery”)

    @Scripts.Render(“~/bundles/bootstrap”)

    @RenderSection(“scripts”, required: false)

head>

After creating an AngularJS bundle and referring to it in _Layout.cshtml, you should be able to use AngularJS in the entire application.

 

Copyright © All Rights Reserved - C# Learners