AngularJS With ASP.NET MVC

AngularJS is a JavaScript framework to create SPA (Single Page Application). It is a client side MV* (MVC+MVVM=MV*) framework. AngularJS extends HTML by providing Directives that add functionality to your markup and that allow you to create powerful dynamic templates for application.

The following are some AngularJS directives which I have used in sample application.

  • ng-app: It is entry point of AngularJS to the page. It shows that the application is AngularJS app.
  • ng-controller: It is directive to define the controller. It attaches a controller class to the view.
  • ng-repeat: It creates loop in your page like foreach loop.
  • angular.module: It is use to create, register and retrieve all angular module.
  • $http: It is an XMLHttpRequest object for requesting external data.
  • $http.get: It read the json data. It takes two parameter url and config but config is optional.
In this article I am going to show a basic example to use AngularJS. I will show you how to create a basic application in MVC 4 with AngularJS.

AngularJS

Step 1
  • Start Visual Studio 2013 or 2012.
  • Create a new project - Web, then click Visual Studio 2012.
  • Select ASP.NET MVC4 Web Application.
  • Provide the Name and Location for the project and click Next.
  • Choose Basic template as project template and click Ok.
Step 2

Create a DataBaseContext class inside Model folder for database factory (insert, update, delete or select the data in database). You can create database and table manually or if you use my approach it will create database and table automatically when you run the application first time because of I have used Code First approach here.

DatabaseContext.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data.Entity;  
  4. using System.Linq;  
  5. using System.Web;  
  6. namespace AngularJSWithMVC.Models  
  7. {  
  8.     public class DatabaseContext: DbContext  
  9.     {  
  10.         public DatabaseContext(): base("DefaultConnection")  
  11.         {}  
  12.         public DbSet < EmployeeModel > EmployeeModels  
  13.         {  
  14.             get;  
  15.             set;  
  16.         }  
  17.     }  
  18. }  
Create another entity class EmployeeModel.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel.DataAnnotations;  
  4. using System.Linq;  
  5. using System.Web;  
  6. namespace AngularJSWithMVC.Models  
  7. {  
  8.     public class EmployeeModel  
  9.     {  
  10.         [Key]  
  11.         public int EmployeeId  
  12.         {  
  13.             get;  
  14.             set;  
  15.         }  
  16.         public string EmployeeName  
  17.         {  
  18.             get;  
  19.             set;  
  20.         }  
  21.         public string Address  
  22.         {  
  23.             get;  
  24.             set;  
  25.         }  
  26.         public string EmailId  
  27.         {  
  28.             get;  
  29.             set;  
  30.         }  
  31.     }  
  32. }  
Web.Config connection string to access database.
  1. <connectionStrings>  
  2.     <add name="DefaultConnection" connectionString="Data Source=(local);DataBase=demodb;user id=sa; password=xyz;" providerName="System.Data.SqlClient" />   
  3.  </connectionStrings>  
And now a controller to show the data on View,
  1. using AngularJSWithMVC.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.Mvc;  
  7. namespace AngularJSWithMVC.Controllers  
  8. {  
  9.     public class EmployeeController: Controller  
  10.     {  
  11.         public ActionResult Index()  
  12.         {  
  13.             return View();  
  14.         }  
  15.         public JsonResult GetAllEmployee()  
  16.         {  
  17.             using(DatabaseContext db = new DatabaseContext())  
  18.             {  
  19.                 var employeeList = db.EmployeeModels.ToList();  
  20.                 return Json(employeeList, JsonRequestBehavior.AllowGet);  
  21.             }  
  22.         }  
  23.     }  
  24. }  
Step 3

Now time to setup AngularJS Module, Service and Controller. So, create a folder with name “AngularScripts” inside the Content folder for clean code.

AppModule.js

Inside AngularScripts folder create a AppModule.js file when you manage your module setting and give it a name as I have given “AngularApp”.

var app = angular.module("AngularApp", []);

Service.js

Create another javascript file “Service.js” for fetching the data from database and provide it to controller. You have to provide a name of the service like “EmployeeService”. Here I am getting the json data from database using GetAllEmployee which will return JsonResult from the EmployeeController.
  1. app.service("EmployeeService", function($http)  
  2. {  
  3.     this.getEmployee = function()  
  4.     {  
  5.         debugger;  
  6.         return $http.get("/employee/getallemployee");  
  7.     };  
  8. });  
Controller.js

You have to create another javascript file to “Controller.js” which will use to show the data on View. Here also you have to provide a unique name for the controller as I have used “EmpCtrl”.
  1. app.controller("EmpCtrl", function($scope, EmployeeService)  
  2. {  
  3.     GetAllEmployee();  
  4.   
  5.     function GetAllEmployee()  
  6.     {  
  7.         debugger;  
  8.         var getAllEmployee = EmployeeService.getEmployee();  
  9.         getAllEmployee.then(function(emp)  
  10.         {  
  11.             $scope.employees = emp.data;  
  12.         }, function()  
  13.         {  
  14.             alert('Data not found');  
  15.         });  
  16.     }  
  17. });  
Step 4

Now time to show the data on View but before that I have to setup AngularJS component and setting on Layout file. Like add all js component which I have created before Service.js, Controller.js etc. Below you can see firstly, all I have used ng-app that denote that It is an angular app and you have to provide the name of app which is already defined in “AngularApp.js”.

I have also used CDN file to use angular feature.

Layout.cshtml
  1. <!DOCTYPE html>  
  2. <html ng-app="AngularApp">  
  3.   
  4. <head>  
  5.     <meta charset="utf-8" />  
  6.     <meta name="viewport" content="width=device-width" />  
  7.     <title>@ViewBag.Title</title>  
  8.     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js"></script>  
  9.     <script src="~/Content/AngularScripts/AppModule.js"></script>  
  10.     <script src="~/Content/AngularScripts/Service.js"></script>  
  11.     <script src="~/Content/AngularScripts/Controller.js"></script> @Styles.Render("~/Content/css") </head>  
  12.   
  13. <body> @RenderBody() @Scripts.Render("~/bundles/jquery") @RenderSection("scripts", required: false) </body>  
  14.   
  15. </html>  
Create a view for EmployeeController’s Index method and add the following code,

Index.cs
  1. @{  
  2.     ViewBag.Title = "Index";  
  3.     Layout = "~/Views/Shared/_Layout.cshtml";  
  4. }<div ng-controller="EmpCtrl">  
  5.     <div>  
  6.         <h2 align="center">Angular JS Basic Example</h2>  
  7.         <h5 align="center">Employee List</h5>  
  8.         <table border="1" cellpadding="10" align="center">  
  9.             <tr>  
  10.                 <td>  
  11.                     Employee Id  
  12.                 </td>  
  13.                 <td>  
  14.                     Employee Name  
  15.                 </td>  
  16.                 <td>  
  17.                     Address  
  18.                 </td>  
  19.                 <td>  
  20.                     Email Id  
  21.                 </td>  
  22.             </tr>  
  23.             <tr ng-repeat="emp in employees">  
  24.                 <td>  
  25.                     {{emp.EmployteeId}}  
  26.                 </td>  
  27.                 <td>  
  28.                     {{emp.EmployeeName}}  
  29.                 </td>  
  30.                 <td>  
  31.                     {{emp.Address}}  
  32.                 </td>  
  33.                 <td>  
  34.                  {{emp.EmailId}}  
  35.                 </td>  
  36.             </tr>  
  37.         </table>  
  38.     </div>  
  39. </div>  
Thanks for reading this article, hope you enjoyed it.

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now