Single Page Application with AngularJS in .NET

I tried to learn about SPAs from online articles and there are some good ones for beginners with mainly CRUD operations for only one database table. In the real world there are many tables you need to retrieve data from and insert into and I couldn't find any such article. So, I have decided to create on my own and I thank my project manager for asking me to show a sample using the AngularJs framework.

This is a two-part demo, in the first part I will be showing how to insert a record into a database and get all the records from the database and display them. Part 2 will show the delete and update operations.

Introduction

These days users want faster web applications with a Rich UI and to be able to access apps from multiple gadgets (like Tablets, Mobiles and so on). HTML5 and jQuery or JavaScript can be used to build Single Page Applications (SPAs).

SPAs

SPAs are web applications that fit in a single page and that provide a more fluid user experience, just like the desktop with a rich UI. SPAs are web apps that load a single HTML page and dynamically update the page as the user interacts with the app.

SPA vs Traditional Web Apps

Traditional Web Apps: You can see in the following image the traditional apps. Whenever the user makes a request, it goes back to the server and renders a new page with a page reload.

magazine
Source: https://msdn.microsoft.com/

SP App

In a SPA when the user requests a page it will load dynamically, calls to the server will be done using Ajax and data is retrieved by JSON. In the SPA the data rendering and routing is done on the client side and that makes it responsive just like desktop apps.

Single Page Application

The following are advantages of SPAs:

  • No page flicker. Native application feel.
  • Client-side routing and data rendering on the client side.
  • Data from the server is in JSON format.

The following are disadvantages of SPAs:

  • User JavaScript must be enabled.
  • Security.

Creating a project in Visual Studio

In this demo I have used Visual Studio 2012, .NET Framework 4.5, AngularJs, Bootstrap and .mdf file for the database operations. I have provided all the necessary screenshots and source code to download.

Open Visual Studio 2012 and create a project with MVC4 template, I have named the project SingePageAngularJS, but you can name it anything you like.

create project with MVC4 template

Adding jQuery and AngularJs

The following figure shows I installed Bootstrap, AngularJs and Angular routing from NuGet packages. And added a new folder to the scripts folder named App and added a new JavaScript file called myApp. I will be adding AngularJs code in myApp later on.

myApp

Now to add these installed files to the MVC project. Go To App_Start, then BundleConfig. Add the following lines as I have shown in the Red rectangle in the following:
BundleConfig

Now you need to ensure these files are added to your Master page (_Layout.cshtml) located in the Views -> Shared folder of the application. I always put my jQuery or required files inside the head tag of the project, to make it accessible to your entire application as in the following image:

JQuery

Now we have added jQuery, Angular, Angular routing, Bootstrap CSS and the bootstrap.js files to our layout page and we need to be sure they are rendered on our browser properly without any errors. To double-check, run the application in the Chrome browser and press F12 to open the browser tools. Check that all the files are loaded by clicking on the Sources tab and check that there are no errors in the console tab. The following confirms that all the files are loaded properly with no errors in the console tab.

console tab
Setting up Database

I will add a .mdf file for the database operations and name it AngularDB.mdf. In the .mdf file I created the two tables EmpDetails and EmpAddress and the scripts are provided below. The EmpDetails table contains employee information and EmpAddress contains the employee's multiple address. Between these two tables we have a foreign key relation with EmpId because whenever you select an employee I wanted to display all the addresses of the specific employee.

EmpDetails Table

  1. CREATE TABLE [dbo].[EmpDetails] (  
  2.    [EmpID] INT IDENTITY (1, 1) NOT NULL,  
  3.    [EmpName] VARCHAR (50) NULL,  
  4.    [EmpPhone] VARCHAR (50) NULL,  
  5.    PRIMARY KEY CLUSTERED ([EmpID] ASC)  
  6. );  
EmpAddress Table 
  1. CREATE TABLE [dbo].[EmpAddress] (  
  2.    [EmpAddressId] INT IDENTITY (1, 1) NOT NULL,  
  3.    [Address1] VARCHAR (500) NULL,  
  4.    [Address2] VARCHAR (500) NULL,  
  5.    [Address3] VARCHAR (500) NULL,  
  6.    [EmpID] INT NULL,  
  7.    PRIMARY KEY CLUSTERED ([EmpAddressId] ASC),  
  8.    FOREIGN KEY ([EmpID]) REFERENCES [dbo].[EmpDetails] ([EmpID])  
  9. );  
Note: In this application my concentration is not only on CRUD operations but also to show how to display data from multiple tables to the UI and pass data to multiple tables.

MVVM Pattern

For this demo I will be using the MVVM pattern for both the AngularJs script and Visual Studio. The following image shows I have created a folder called ViewModels (it has references of multiple models) and added two models in the models folder. I named them EmpDetailsModel and EmpAddressModel.

MVVM Pattern

AngularJs Code

In the previous section we did some database related stuff. Now we jump into the main topic of this demo.

In Adding jQuery and AngularJs: We have created the myApp.js file and left it empty, now just copy and paste the following code into it.
  1. angular.module('App', ['AngularDemo.EmpAddController',  
  2.                        'AngularDemo.AddressController',  
  3.                        'AngularDemo.DeleteController'  
  4. ])  
  5.   
  6. .config(['$routeProvider''$locationProvider', function ($routeProvider, $locationProvider) {  
  7.   
  8.     $routeProvider.when('/', {  
  9.         templateUrl: '/Home/AddEmployee',  
  10.         controller: 'EmpAddCtrl',  
  11.     });  
  12.     $routeProvider.when('/Edit', {  
  13.         templateUrl: '/Home/EditEmployee',  
  14.         controller: 'EditCtrl'  
  15.     });  
  16.     $routeProvider.when('/Delete', {  
  17.         templateUrl: '/Home/DeleteEmployee',  
  18.         controller: 'DeleteCtrl'  
  19.     });  
  20.     $routeProvider.otherwise({  
  21.         redirectTo: '/'  
  22.     });  
  23.     // Specify HTML5 mode (using the History APIs) or HashBang syntax.  
  24.     $locationProvider.html5Mode(false).hashPrefix('!');  
  25.   
  26. }]);  
  27.   
  28. //Add Employee Controller  
  29. angular.module('AngularDemo.EmpAddController', ['ngRoute'])  
  30. .controller('EmpAddCtrl', function ($scope, $http) {  
  31.   
  32.     $scope.EmpAddressList = {};  
  33.     $http.get('/Home/ShowEmpList').success(function (data) {  
  34.         $scope.EmpAddressList = data;  
  35.         
  36.     });  
  37.   
  38.   
  39.     $scope.EmpDetailsModel =  
  40.      {  
  41.          EmpID: '',  
  42.          EmpName: '',  
  43.          EmpPhone: ''  
  44.      };  
  45.   
  46.     $scope.EmpAddressModel =  
  47.     {  
  48.         Address1: '',  
  49.         Address2: '',  
  50.         Address3: ''  
  51.     };  
  52.   
  53.     $scope.EmployeeViewModel = {  
  54.         empDetailModel: $scope.EmpDetailsModel,  
  55.         empAddressModel: $scope.EmpAddressModel  
  56.     };  
  57.   
  58.   
  59.     $scope.AddEmployee = function () {  
  60.         //debugger;  
  61.         $.ajax({  
  62.             url: '/Home/AddEmpDetails',  
  63.             type: 'POST',  
  64.             dataType: 'json',  
  65.             contentType: 'application/json',  
  66.             traditional: true,  
  67.             data: JSON.stringify({ EmployeeViewModelClient: $scope.EmployeeViewModel }),  
  68.             success: function (data) {  
  69.                 $scope.EmpAddressList.push(data[0]);  
  70.                 $scope.$apply();  
  71.                 //$scope.$apply();  
  72.                 alert("Record is been added");  
  73.             }  
  74.         });  
  75.     };  
  76. });  
  77.   
  78.   
  79. //Address Controller  
  80. angular.module('AngularDemo.AddressController', ['ngRoute'])  
  81. .controller('EditCtrl', function ($scope, $http) {  
  82.     $scope.Message = "Edit in Part 2 is coming soon";  
  83. });  
  84.   
  85. angular.module('AngularDemo.DeleteController', ['ngRoute'])  
  86. .controller('DeleteCtrl', function ($scope, $http) {  
  87.     $scope.Message = "Delete in Part 2 is coming soon";  
  88. });  
Angular Code Explanation
  1. angular.module('App', ['AngularDemo.EmpAddController',  
  2. 'AngularDemo.AddressController',  
  3. 'AngularDemo.DeleteController'  
  4. ])  
Note: The angular.module is a global place for creating, registering and retrieving Angular modules. All modules that should be available to an application must be registered using this mechanism.

The first parameter is the name of your Angular app, for our demo it is named "App".

The second parameter is an array of dependencies, we have only two dependencies, currently they are:

'AngularDemo.EmpAddController', 'AngularDemo.AddressController' and 'AngularDemo.DeleteController'.

ng-app directive

Once you name your AngularJs you need to use it in your HTML page depending upon your requirements. For this demo I have used ng-app in the _Layout page in the HTML tag as in the following code snippet:

app directive

Client-side Routing

So, we have defined the name of our AngularJs app and specified an array of dependencies. Now, let’s create the routing at the client side. For this I have created three routes as in the following with templateUrl and controller.
  1. .config(['$routeProvider''$locationProvider', function ($routeProvider, $locationProvider) {  
  2.   
  3.     $routeProvider.when('/', {  
  4.         templateUrl: '/Home/AddEmployee',  
  5.         controller: 'EmpAddCtrl',  
  6.     });  
  7.     $routeProvider.when('/Edit', {  
  8.         templateUrl: '/Home/EditEmployee',  
  9.         controller: 'EditCtrl'  
  10.     });  
  11.     $routeProvider.when('/Delete', {  
  12.         templateUrl: '/Home/DeleteEmployee',  
  13.         controller: 'DeleteCtrl'  
  14.     });  
  15.     $routeProvider.otherwise({  
  16.         redirectTo: '/'  
  17.     });  
  18.     // Specify HTML5 mode (using the History APIs) or HashBang syntax.  
  19.     $locationProvider.html5Mode(false).hashPrefix('!');  
  20.   
  21. }]);  
Whenever AngularJs finds the URL that was specified in routing, it goes to the corresponding AngularJs controller, where we need to create models and Ajax calls to the server. The following is the controller code:
  1. //Add and display Employee Controller  
  2. angular.module('AngularDemo.EmpAddController', ['ngRoute'])  
  3. .controller('EmpAddCtrl', function ($scope, $http) {  
  4.   
  5. $scope.EmpDetailsModel =  
  6.      {  
  7.          EmpID: '',  
  8.          EmpName: '',  
  9.          EmpPhone: ''  
  10.      };  
  11.   
  12.     $scope.EmpAddressModel =  
  13.     {  
  14.         Address1: '',  
  15.         Address2: '',  
  16.         Address3: ''  
  17.     };  
  18.   
  19.     $scope.EmployeeViewModel = {  
  20.         empDetailModel: $scope.EmpDetailsModel,  
  21.         empAddressModel: $scope.EmpAddressModel  
  22.     };  
  23.   
  24.     $scope.EmpAddressList = {};  
  25.     $http.get('/Home/ShowEmpList').success(function (data) {  
  26.         $scope.EmpAddressList = data;  
  27.     });  
  28.      
  29.     $scope.AddEmployee = function () {  
  30.         $.ajax({  
  31.             url: '/Home/AddEmpDetails',  
  32.             type: 'POST',  
  33.             dataType: 'json',  
  34.             contentType: 'application/json',  
  35.             traditional: true,  
  36.             data: JSON.stringify({ EmployeeViewModelClient: $scope.EmployeeViewModel }),  
  37.             success: function (data) {  
  38.                 $scope.EmpAddressList.push(data[0]);  
  39.                 $scope.$apply();  
  40.                 alert("Record is been added");  
  41.             }  
  42.         });  
  43.     };  
  44. });  
$scope is responsible for setting the model properties and the functions/behaviour of the specific controller.

In the EmpAddCtrl controller we have two models (EmpDetailsModel and EmpAddressModel) and viewmodel (EmployeeViewModel) where we will be passing this viewmodel to the server to save data to the database, using the $scope.AddEmployee function and $http.get will get the list of all records on pageloads.

Views

Now we are done with AngularJs. We need to use this in HTML pages. So, this is what my _layout page looks like.

_Layout.html
  1. <!DOCTYPE html>  
  2. <html lang="en" ng-app="App">  
  3. <head>  
  4.     <meta charset="utf-8" />  
  5.     <title>@ViewBag.Title - My ASP.NET MVC Application</title>  
  6.     <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />  
  7.     <meta name="viewport" content="width=device-width" />  
  8.     @Styles.Render("~/Content/css")  
  9.     @Scripts.Render("~/bundles/jquery")  
  10.     @Scripts.Render("~/bundles/bootstrap")  
  11.     @Scripts.Render("~/bundles/angular")  
  12.     @Scripts.Render("~/bundles/CustomAngular")  
  13.     @Scripts.Render("~/bundles/modernizr")  
  14. </head>  
  15. <body>  
  16.     <header>  
  17.         <nav class="navbar navbar-default navbar-static-top">  
  18.             <div class="container">  
  19.                 <div class="navbar-header">  
  20.                     <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">  
  21.                         <span class="sr-only">Toggle navigation</span>  
  22.                         <span class="icon-bar"></span>  
  23.                         <span class="icon-bar"></span>  
  24.                         <span class="icon-bar"></span>  
  25.                     </button>  
  26.                                     </div>  
  27.                 <div id="navbar" class="navbar-collapse collapse">  
  28.                     <ul class="nav navbar-nav">  
  29.                         <li class="active"><a href="#!/">Add</a></li>  
  30.                         <li><a href="#!/Address">Edit/Update</a></li>  
  31.                         <li><a href="#!/Delete">Delete</a></li>  
  32.                     </ul>  
  33.                       
  34.                 </div>  
  35.                 <!--/.nav-collapse -->  
  36.             </div>  
  37.         </nav>  
  38.     </header>  
  39.     <div id="body">  
  40.         @RenderSection("featured", required: false)  
  41.         <section class="content-wrapper main-content clear-fix">  
  42.             @RenderBody()  
  43.         </section>  
  44.     </div>  
  45.   
  46.     @RenderSection("scripts", required: false)  
  47.   
  48.   
  49. </body>  
  50. </html>  
Index.html page

Just copy the following code and paste it into the index HTML page. ng-view is a place holder where the partial views are dynamically loaded.
  1. <div ng-view="" ></div>  
AddEmployee.html partial page

Copy the following code and paste it into your AddEmployee partial view. In this view the user can add a new employee and address information and it also displays a list of employees in grid format.

The ng-model directive binds the value of HTML controls (input, select and textarea) to the application data.
  1. <div style="width: 50%; margin: 50px auto;">  
  2.   
  3.     <table>  
  4.         <tr>  
  5.             <td>  
  6.                 <strong>Employee Name:</strong>  
  7.             </td>  
  8.             <td>  
  9.                 <input type="text" class="form-control" ng-model="EmpDetailsModel.EmpName" placeholder="Employee Name" />  
  10.             </td>  
  11.         </tr>  
  12.         <tr>  
  13.             <td>  
  14.                 <strong>Employee Phone:</strong>  
  15.   
  16.             </td>  
  17.             <td>  
  18.                 <input type="text" class="form-control" ng-model="EmpDetailsModel.EmpPhone" placeholder="Employee Phone" />  
  19.             </td>  
  20.         </tr>  
  21.         <tr>  
  22.             <td>  
  23.                 <strong>Address 1:</strong>  
  24.   
  25.             </td>  
  26.             <td>  
  27.                 <input type="text" class="form-control" ng-model="EmpAddressModel.Address1" placeholder="Address 1" />  
  28.             </td>  
  29.         </tr>  
  30.         <tr>  
  31.             <td>  
  32.                 <strong>Address 2:</strong>  
  33.   
  34.             </td>  
  35.             <td>  
  36.                 <input type="text" class="form-control" ng-model="EmpAddressModel.Address2" placeholder="Address 2" />  
  37.             </td>  
  38.         </tr>  
  39.   
  40.         <tr>  
  41.             <td>  
  42.                 <strong>Address 3:</strong>  
  43.   
  44.             </td>  
  45.             <td>  
  46.                 <input type="text" class="form-control" ng-model="EmpAddressModel.Address3" placeholder="Address 3" />  
  47.             </td>  
  48.         </tr>  
  49.         <br />  
  50.         <tr>  
  51.             <td>      
  52.             </td>  
  53.             <td>  
  54.                 <button type="button" ng-click="AddEmployee();" class="btn btn-primary">Save</button>  
  55.             </td>  
  56.         </tr>  
  57.   
  58.     </table>  
  59. </div>  
  60.   
  61. <hr style="color: black" />  
  62.   
  63. <div style="width: 50%; margin: 50px auto;">  
  64.     <div class="panel panel-default">  
  65.         <!-- Default panel contents -->  
  66.         <div class="panel-heading"><b>Employee Details </b></div>  
  67.         <div class="table-responsive">  
  68.             <table id="EmployeeTable" class="table table-striped table-bordered table-hover table-condensed">  
  69.                 <thead>  
  70.                     <tr>  
  71.                         <th>Employee Name</th>  
  72.                         <th>Employee Phone</th>  
  73.                         <th>Employee Address1</th>  
  74.                         <th>Employee Address2</th>  
  75.                         <th>Employee Address3</th>  
  76.                     </tr>  
  77.                 </thead>  
  78.                 <tbody>  
  79.                     <tr data-ng-repeat="Emp in EmpAddressList">  
  80.   
  81.                         <td>{{Emp.empDetailModel.EmpName}}</td>  
  82.                         <td>{{Emp.empDetailModel.EmpPhone}}</td>  
  83.                         <td>{{Emp.empAddressModel.Address1}}</td>  
  84.                         <td>{{Emp.empAddressModel.Address2}}</td>  
  85.                         <td>{{Emp.empAddressModel.Address3}}</td>  
  86.   
  87.                     </tr>  
  88.   
  89.                     @*<tr ng-if="states.NewRow">*@  
  90.                     <tr ng-if="EmpAddressList.length == 0">  
  91.                         <td class="text-center" colspan="4">There are no Employee details to display  
  92.                         </td>  
  93.                     </tr>  
  94.                 </tbody>  
  95.             </table>  
  96.   
  97.         </div>  
  98.     </div>  
  99.       
  100. </div>  
Output screens

Now we are done with all our coding. Run it by pressing F5, you can see the following screenshot. Initially we don't have any data, therefore it displays There are no Employee details to display.

Output screens

Save Button

Enter the data of an employee and their address(es), when the user clicks the Save button, it triggers the AddEmployee function in AngularJs that calls the corresponding controller action. The following image shows that we have entered information.

Save Button
Once the user clicks on Save, the view model is passed from AngularJs to the MVC controller action. I have the following two screenshots to show the data being passed to the models (empDetailsModel and empAddressModel).

empDetailsModel

empAddressModel

After saving into the database you will get confirmation saying the record has been added.

confirmation
Database

The data we have entered into the UI has been saved to the database.

Database
Conclusion

A Single Page Application will provide you better performance compared to traditional web apps, but never compromise when it comes to security and you should think about security and implement sufficient measures for it before developing Single Page Applications.

Up Next
    Ebook Download
    View all
    Learn
    View all