Performing CRUD Operations Using AngularJS In MVC

Introduction

AngularJS is a Superheroic JavaScript MVW (Model-View-Whatever) /Binding Framework that is used for making rich and extensible web applications. It is especially used for Single Page Application (SPA) projects. It extends HTML DOM with additional attributes and makes it more responsive to user actions. The AngularJS is open source.

Note "AngularJS helps us binding HTML elements to JavaScript objects."

Data Binding

AngularJS uses two-way data-binding. Data-binding is an automatic process of updating the View whenever a Model changes, as well as updating the Model whenever a View changes.

ASP.NET
Figure 1: AngularJS Binding

Controller

AngularJS defines Controller using ng-controller directive. AngularJS creates a new instance object internally and binds it. Controller is attached to the DOM via the ng-controller directive. $scope is a special JavaScript object which plays the role of joining Controller to the Views. $scope refers to the application which is desired to use the Controller object.

Services

Services are JavaScript functions and are responsible to perform specific tasks only. AngularJS services are:

  1. Lazily instantiated
    AngularJS only instantiates a service when an application component depends on it.

  2. Singletons
    Each component dependent on a service gets a reference to the single instance generated by the service factory.

$scope is Angular service for Angular scope management. $scope is defined as parameter. Angular will automatically come and inject the $scope. This term is call Dependency Injection (DI). AngularJS provides many in-built services. For example, $https:, $route, $window, $location etc. Each service is responsible for a specific task - $https is used to make AJAX call to get the server data; $route is used to define the routing information and so on. Inbuilt services are always prefixed with $ symbol.

Let's code

We are creating a sample web application in C# along with AngularJS, using Visual Studio 2017. This application will have the following features.

  1. Binding the data and showing in table list.
  2. Create, Edit and Update user.
  3. Create a Controller, services, and modules.

First of all, we will create a new web application in VS2017. We will install AngularJS using nuGet package, as shown below.

ASP.NET
Figure 2: Nuget for AngularJS

We need to create UserViewModel class in C#.

  1. var userApp = angular.module("userApp", []);  
  2. We Create UserServices.js file   
  3. userApp.service("userService"function ($http) {  
  4.     var $this = this;  
  5.     $this.AddEdit = function (user) {  
  6.         var request = $http({  
  7.             method: 'POST',  
  8.             url: Domain + 'AddEditUser',  
  9.             data: JSON.stringify(user),  
  10.             dataType: "json"  
  11.         });  
  12.         return request;  
  13.     }  
  14.    
  15.     $this.Delete = function (id) {  
  16.         var request = $http({  
  17.             method: 'POST',  
  18.             url: Domain + 'DeleteUser',  
  19.             data: "{ id:" + id + " }",  
  20.             dataType: "json"  
  21.         });  
  22.         return request;  
  23.     }  
  24.    
  25.     $this.GetAll = function () {  
  26.         var request = $http({  
  27.             method: 'GET',  
  28.             url: Domain + 'GetAllUsers',  
  29.         });  
  30.         return request;  
  31.     }  
  32.    
  33.     $this.GetUser = function (id) {  
  34.         var request = $http({  
  35.             method: 'GET',  
  36.             url: Domain + 'GetUser/' + id,  
  37.         });  
  38.         return request;  
  39.     }  
  40. });   

Create UserController.js file 

  1. userApp.controller("userController"function ($scope, userService) {  
  2.    
  3.     GetUsers();  
  4.    
  5.     $scope.SaveUser = function () {  
  6.         var UserModel = {  
  7.             Id: $scope.id,  
  8.             Email: $scope.email,  
  9.             FirstName: $scope.firstName,  
  10.             LastName: $scope.lastName,  
  11.             Phone: $scope.phone  
  12.         };  
  13.         if (!CheckIsValid()) {  
  14.             alert('Please fill the detail!');  
  15.             return false;  
  16.         }  
  17.         var requestResponse = userService.AddEdit(UserModel);  
  18.         Message(requestResponse);  
  19.     };  
  20.    
  21.     $scope.editUser = function (id) {  
  22.         var getData = userService.GetUser(id);  
  23.         getData.then(function (user) {  
  24.             var userData = user.data;  
  25.             $scope.id = userData.Id;  
  26.             $scope.email = userData.Email;  
  27.             $scope.phone = userData.Phone;  
  28.         },  
  29.             function () {  
  30.                 alert('Error in getting records');  
  31.             });  
  32.     }  
  33.    
  34.     $scope.DeleteUser = function (id) {  
  35.         var requestResponse = userService.Delete(id);  
  36.         Message(requestResponse);  
  37.     };  
  38.    
  39.     function GetUsers() {  
  40.         var requestResponse = userService.GetAll();  
  41.         requestResponse.then(function (response) {  
  42.             $scope.employees = response.data;  
  43.         }, function () {  
  44.    
  45.         })  
  46.     };  
  47.    
  48.     function Message(requestResponse) {  
  49.         requestResponse.then(function successCallback(response) {  
  50.             GetUsers();  
  51.             $('#addEditUser').modal('hide');  
  52.             // this callback will be called asynchronously  
  53.             // when the response is available  
  54.         }, function errorCallback(response) {  
  55.             // called asynchronously if an error occurs  
  56.             // or server returns response with an error status.  
  57.         });  
  58.     }  
  59.    
  60.     function CheckIsValid() {  
  61.         var isValid = true;  
  62.         if ($('#email').val() === '' || $('#phone').val() === '' || $('#email').val() === '' || $('#phone').val() === '') {  
  63.             isValid = false;  
  64.         }  
  65.         return isValid;  
  66.     }  
  67. });  

Now, we will create a Controller for the UI that handles all requests for user (add/edit/delete) and show the user list along with a View HTML template The following is the code snippet for UserController and Views.

  1. using CURD.Code;  
  2. using CURD.Models;  
  3. using System.Collections.Generic;  
  4. using System.Web.Mvc;  
  5.    
  6. namespace CURD.Controllers  
  7. {  
  8.     public class UserController : Controller  
  9.     {  
  10.         [HttpGet]  
  11.         public ActionResult Index()  
  12.         {  
  13.             return View();  
  14.         }  
  15.    
  16.         [HttpPost]  
  17.         public JsonResult AddEditUser(UserViewModel model)  
  18.         {  
  19.             if (ModelState.IsValid)  
  20.             {  
  21.                 if (model.Id.HasValue)  
  22.                 {  
  23.                     StaticData.Update(model);  
  24.                 }  
  25.                 else  
  26.                 {  
  27.                     StaticData.Save(model);  
  28.                 }  
  29.             }  
  30.             string status = model.Id.HasValue ? "updated" : "saved";  
  31.             string message = $"User has been { status } successfully!";  
  32.             return Json(message, JsonRequestBehavior.AllowGet);  
  33.         }  
  34.    
  35.         [HttpPost]  
  36.         public JsonResult DeleteUser(int id)  
  37.         {  
  38.             StaticData.Delete(id);  
  39.             string message = $"User has been removed successfully!";  
  40.             return Json(message, JsonRequestBehavior.AllowGet);  
  41.         }  
  42.    
  43.         [HttpGet]  
  44.         public JsonResult GetAllUsers()  
  45.         {  
  46.             List<UserViewModel> users = StaticData.UserList;  
  47.             return Json(users, JsonRequestBehavior.AllowGet);  
  48.         }  
  49.    
  50.         [HttpGet]  
  51.         public JsonResult GetUser(int id)  
  52.         {  
  53.             UserViewModel userViewModel = StaticData.Find(id);  
  54.             return Json(userViewModel, JsonRequestBehavior.AllowGet);  
  55.         }  
  56.     }  
  57. }  
  58.   
  59. @{  
  60.     ViewBag.Title = "CURD with angular!";  
  61. }  
  62. <div ng-controller="userController">  
  63.     <div class="form-group">  
  64.         <button type="button" class="btn btn-success" data-target="#addEditUser" data-toggle="modal"><i class="fa fa-plus"> </i> Add New</button>  
  65.     </div>  
  66.     <table class="table table-bordered table-condensed table-hover table-responsive">  
  67.         <thead>  
  68.             <tr>  
  69.                 <td>Id</td>  
  70.                 <td>Email</td>  
  71.                 <td>First Name</td>  
  72.                 <td>Last Name</td>  
  73.                 <td>Phone</td>  
  74.                 <td>Created Date</td>  
  75.                 <td>Action</td>  
  76.             </tr>  
  77.         </thead>  
  78.         <tr ng-repeat="employee in employees">  
  79.             <td>{{employee.Id}}</td>  
  80.             <td>{{employee.Email}}</td>  
  81.             <td>{{employee.FirstName}}</td>  
  82.             <td>{{employee.LastName}}</td>  
  83.             <td>{{employee.Phone}}</td>  
  84.             <td>{{employee.CreatedDate}}</td>  
  85.             <td>  
  86.                 <button class="btn btn-xs btn-default" data-target="#addEditUser" data-toggle="modal" ng-click="editUser(employee.Id)"><i class="fa fa-edit"></i></button>  
  87.                 <button class="btn btn-xs btn-danger" ng-click="DeleteUser(employee.Id)"><i class="fa fa-trash"></i></button>  
  88.             </td>  
  89.         </tr>  
  90.     </table>  
  91.     <div id="addEditUser" class="modal fade" role="dialog">  
  92.         <div class="modal-dialog">  
  93.             <div class="modal-content">  
  94.                 <div class="modal-header">  
  95.                     <button type="button" class="close" data-dismiss="modal">×</button>  
  96.                     <h4 class="modal-title">Add Detail</h4>  
  97.                 </div>  
  98.                 <div class="modal-body">  
  99.                     <input type="hidden" class="form-control" ng-model="id">  
  100.                     <div class="form-group">  
  101.                         <label for="email">Email address:</label>  
  102.                         <input type="email" class="form-control" id="email" ng-model="email" maxlength="50">  
  103.                     </div>  
  104.                     <div class="form-group">  
  105.                         <label for="firstName">FirstName:</label>  
  106.                         <input type="text" class="form-control" id="firstName" ng-model="firstName" maxlength="100">  
  107.                     </div>  
  108.                     <div class="form-group">  
  109.                         <label for="lastName">LastName:</label>  
  110.                         <input type="text" class="form-control" id="lastName" ng-model="lastName" maxlength="100">  
  111.                     </div>  
  112.                     <div class="form-group">  
  113.                         <label for="phone">Phone:</label>  
  114.                         <input type="text" class="form-control" id="phone" ng-model="phone" maxlength="10">  
  115.                     </div>  
  116.    
  117.                 </div>  
  118.                 <div class="modal-footer">  
  119.                     <button type="button" class="btn btn-default" data-dismiss="modal"><i class="fa fa-close"></i> Close</button>  
  120.                     <button type="submit" class="btn btn-success" ng-click="SaveUser()"><i class="fa fa-save"></i> Submit</button>  
  121.                 </div>  
  122.             </div>  
  123.         </div>  
  124.     </div>  
  125. </div>   

Now, run the application. The starting page shows the user list. Click on "Add New" button. This renders a new modal popup; fill in the details and Save.

ASP.NET
Figure 3: User Listing

ASP.NET
Figure 4: Add User

Download

We can download the complete source code too.

 

X

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

Start Learning Now