ASP.NET MVC 5 With AngularJS - Part 2

In this topic we will see an overview on AngularJS. After getting an overview we will create an ASP.NET MVC application with implementing AngularJS(v1.4.8).

If you missed the previous article in this series please go and have an overview before getting into this part.

Introduction

In our previous article we saw an overview on AngularJS. Now we know what AngularJS is capable of, what is it, and how to start with it. Now it’s time to make a sample application which can perform CRUD operations using database. Ok, let's get started.

AngularJS with Visual Studio

Let’s open Visual Studio 2015(IDE) click: File, New, then Project. After that a new window will appear like the following image.

Web application
                                                          Figure 1.0

Click on ASP.NET Web Application, rename the application and hit “OK” button at bottom right. Choose empty template in next window and click on “ok” button. It will take a while to load a sample empty project.

Now the first thing we need to do is register AngularJS.Core in this application. We need to get reference from NuGet.

To do that right click on project name and click on “Manage NuGet Packages” like the following image,

Manage Newget Package
                                Figure 1.1

And in next window browse searching “Angular” and install the updated version of AngularJS.Core like the following image.

AngularJS
                                                                    Figure 1.2

Or click on Tools, NuGet Package Manager > Package Manager Console and write Install-Package AngularJS.Core.

Also we need to add jQuery library in our project like below.

JQuery
                                                              Figure 1.3

Our installation process is done. Now test it with our previous AngularJS code in comparsion with jQuery section.

Data Layer

  1. public class GenericRepository < T > : IRepository < T > whereT: class  
  2. {  
  3.     CRUD_SampleEntities context = null;  
  4.     private DbSet < T > entities = null;  
  5.     public GenericRepository(CRUD_SampleEntities context)  
  6.     {  
  7.         this.context = context;  
  8.         entities = context.Set < T > ();  
  9.     }  
  10.     ///<summary>  
  11.     /// Get Data From Database  
  12.     ///<para>Use it when to retive data through a stored procedure</para>  
  13.     ///</summary>  
  14.     public IEnumerable < T > ExecuteQuery(stringspQuery, object[] parameters)  
  15.     {  
  16.         using(context = newCRUD_SampleEntities())  
  17.         {  
  18.             returncontext.Database.SqlQuery < T > (spQuery, parameters).ToList();  
  19.         }  
  20.     }  
  21.     ///<summary>  
  22.     /// Get Single Data From Database  
  23.     ///<para>Use it when to retive single data through a stored procedure</para>  
  24.     ///</summary>  
  25.     public TExecuteQuerySingle(stringspQuery, object[] parameters)  
  26.     {  
  27.         using(context = newCRUD_SampleEntities())  
  28.         {  
  29.             returncontext.Database.SqlQuery < T > (spQuery, parameters).FirstOrDefault();  
  30.         }  
  31.     }  
  32.     ///<summary>  
  33.     /// Insert/Update/Delete Data To Database  
  34.     ///<para>Use it when to Insert/Update/Delete data through a stored procedure</para>  
  35.     ///</summary>  
  36.     public int ExecuteCommand(stringspQuery, object[] parameters)  
  37.     {  
  38.         int result = 0;  
  39.         try  
  40.         {  
  41.             using(context = newCRUD_SampleEntities())  
  42.             {  
  43.                 result = context.Database.SqlQuery < int > (spQuery, parameters).FirstOrDefault();  
  44.             }  
  45.         }  
  46.         catch  
  47.         {}  
  48.         return result;  
  49.     }  
  50.     private bool disposed = false;  
  51.     protected virtual void Dispose(bool disposing)  
  52.     {  
  53.         if (!this.disposed)  
  54.         {  
  55.             if (disposing)  
  56.             {  
  57.                 context.Dispose();  
  58.             }  
  59.         }  
  60.         this.disposed = true;  
  61.     }  
  62.     public void Dispose()  
  63.     {  
  64.         Dispose(true);  
  65.         GC.SuppressFinalize(this);  
  66.     }  
  67. }  
Interface:
  1. interface IRepository<T> : IDisposablewhereT : class  
  2. {  
  3.    IEnumerable<T>ExecuteQuery(stringspQuery, object[] parameters);  
  4.    TExecuteQuerySingle(stringspQuery, object[] parameters);  
  5.    intExecuteCommand(stringspQuery, object[] parameters);  
  6. }  
Code Explanation:

If you are new to this design pattern overview click here for more.

Middle Layer:
  1. public partial class CustomerService  
  2. {  
  3.     private GenericRepository < Customer > CustRepository;  
  4.     public CustomerService()  
  5.     {  
  6.         this.CustRepository = newGenericRepository < Customer > (newCRUD_SampleEntities());  
  7.     }  
  8.     public IEnumerable < Customer > GetAll(object[] parameters)  
  9.     {  
  10.         stringspQuery = "[Get_Customer] {0}";  
  11.         returnCustRepository.ExecuteQuery(spQuery, parameters);  
  12.     }  
  13.     public CustomerGetbyID(object[] parameters)  
  14.     {  
  15.         stringspQuery = "[Get_CustomerbyID] {0}";  
  16.         returnCustRepository.ExecuteQuerySingle(spQuery, parameters);  
  17.     }  
  18.     public int Insert(object[] parameters)  
  19.     {  
  20.         stringspQuery = "[Set_Customer] {0}, {1}";  
  21.         returnCustRepository.ExecuteCommand(spQuery, parameters);  
  22.     }  
  23.     public int Update(object[] parameters)  
  24.     {  
  25.         stringspQuery = "[Update_Customer] {0}, {1}, {2}";  
  26.         returnCustRepository.ExecuteCommand(spQuery, parameters);  
  27.     }  
  28.     public int Delete(object[] parameters)  
  29.     {  
  30.         stringspQuery = "[Delete_Customer] {0}";  
  31.         returnCustRepository.ExecuteCommand(spQuery, parameters);  
  32.     }  
  33. }  
Our Data Layer and Service layer is ready. For creating database, please download the database script and execute it using MS SQL Server.

Let’s create a MVC HomeController and generate empty view.

Add controller
                                              Figure: 1.4

MVC HomeController
  1. public class HomeController: Controller  
  2. {  
  3.     private CustomerServiceobjCust;  
  4.     public HomeController()  
  5.     {  
  6.         this.objCust = newCustomerService();  
  7.     }  
  8.     // GET: Home  
  9.     public ActionResult Index()  
  10.     {  
  11.         return View();  
  12.     }  
  13.     // GET: All Customer  
  14.     [HttpGet]  
  15.     public JsonResultGetAllData()  
  16.     {  
  17.         int Count = 10;  
  18.         IEnumerable < object > customers = null;  
  19.         try  
  20.         {  
  21.             object[] parameters = {  
  22.                 Count  
  23.             };  
  24.             customers = objCust.GetAll(parameters);  
  25.         }  
  26.         catch  
  27.         {}  
  28.         returnJson(customers.ToList(), JsonRequestBehavior.AllowGet);  
  29.     }  
  30.     // GET: Get Single Customer  
  31.     [HttpGet]  
  32.     public JsonResultGetbyID(int id)  
  33.     {  
  34.         object customer = null;  
  35.         try  
  36.         {  
  37.             object[] parameters = {  
  38.                 id  
  39.             };  
  40.             customer = this.objCust.GetbyID(parameters);  
  41.         }  
  42.         catch  
  43.         {}  
  44.         return Json(customer, JsonRequestBehavior.AllowGet);  
  45.     }  
  46.     public ActionResult Insert()  
  47.     {  
  48.         return View();  
  49.     }  
  50.     // POST: Save New Customer  
  51.     [HttpPost]  
  52.     public JsonResult Insert(Customer model)  
  53.     {  
  54.         int result = 0;  
  55.         bool status = false;  
  56.         if (ModelState.IsValid)  
  57.         {  
  58.             try  
  59.             {  
  60.                 object[] parameters = {  
  61.                     model.CustName,  
  62.                     model.CustEmail  
  63.                 };  
  64.                 result = objCust.Insert(parameters);  
  65.                 if (result == 1)  
  66.                 {  
  67.                     status = true;  
  68.                 }  
  69.                 returnJson(new  
  70.                 {  
  71.                     success = status  
  72.                 });  
  73.             }  
  74.             catch  
  75.             {}  
  76.         }  
  77.         return Json(new  
  78.         {  
  79.             success = false,  
  80.                 errors = ModelState.Keys.SelectMany(i => ModelState[i].Errors).Select(m => m.ErrorMessage).ToArray()  
  81.         });  
  82.     }  
  83.     public ActionResult Update()  
  84.     {  
  85.         return View();  
  86.     }  
  87.     // POST: Update Existing Customer  
  88.     [HttpPost]  
  89.     public JsonResult Update(Customer model)  
  90.     {  
  91.         int result = 0;  
  92.         bool status = false;  
  93.         if (ModelState.IsValid)  
  94.         {  
  95.             try  
  96.             {  
  97.                 object[] parameters = {  
  98.                     model.Id,  
  99.                     model.CustName,  
  100.                     model.CustEmail  
  101.                 };  
  102.                 result = objCust.Update(parameters);  
  103.                 if (result == 1)  
  104.                 {  
  105.                     status = true;  
  106.                 }  
  107.                 returnJson(new  
  108.                 {  
  109.                     success = status  
  110.                 });  
  111.             }  
  112.             catch  
  113.             {}  
  114.         }  
  115.         return Json(new  
  116.         {  
  117.             success = false,  
  118.                 errors = ModelState.Keys.SelectMany(i => ModelState[i].Errors).Select(m => m.ErrorMessage).ToArray()  
  119.         });  
  120.     }  
  121.     // DELETE: Delete Customer  
  122.     [HttpDelete]  
  123.     public JsonResult Delete(int id)  
  124.     {  
  125.         int result = 0;  
  126.         bool status = false;  
  127.         try  
  128.         {  
  129.             object[] parameters = {  
  130.                 id  
  131.             };  
  132.             result = objCust.Delete(parameters);  
  133.             if (result == 1)  
  134.             {  
  135.                 status = true;  
  136.             }  
  137.         }  
  138.         catch  
  139.         {}  
  140.         return Json(new  
  141.         {  
  142.             success = status  
  143.         });  
  144.     }  
  145.     protected override void Dispose(bool disposing)  
  146.     {  
  147.         base.Dispose(disposing);  
  148.     }  
  149. }  
Code Explanation

Let’s explaine the code part by part.

Get All Records: Below code sample is to get all records from database by using our middle layer/service layer. We are returning JSON data here. The format of JSON data is easy to read, follow attribute-value pairs.

Initially we are getting ten (10) records, this is plan for paging in view page.
  1. // GET: All Customer  
  2. [HttpGet]  
  3. public JsonResultGetAllData()  
  4. {  
  5.     int Count = 10;  
  6.     IEnumerable < object > customers = null;  
  7.     try  
  8.     {  
  9.         object[] parameters = {  
  10.             Count  
  11.         };  
  12.         customers = objCust.GetAll(parameters);  
  13.     }  
  14.     catch  
  15.     {}  
  16.     return Json(customers.ToList(), JsonRequestBehavior.AllowGet);  
  17. }  
While we are returning the list data we have set “JsonRequestBehavior.AllowGet”. if we miss that, this error message will appear:

This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.

Why use it? If you read that message carefully the answer is there. This is for security reasons.

Get Single Record Details: Below code sample will retrieve a single selected record details from database, which also returning JSON data format.
  1. // GET: Get Single Customer  
  2. [HttpGet]  
  3. public JsonResultGetbyID(int id)  
  4. {  
  5.     object customer = null;  
  6.     try  
  7.     {  
  8.         object[] parameters = {  
  9.             id  
  10.         };  
  11.         customer = this.objCust.GetbyID(parameters);  
  12.     }  
  13.     catch  
  14.     {}  
  15.     return Json(customer, JsonRequestBehavior.AllowGet);  
  16. }  
Insert Records: Below code sample will Insert/save record details to database, which is returning a JSON result of boolean data type.

If it’s true then it indicate that data inserted to database successfully.
  1. // POST: Save New Customer  
  2. [HttpPost]  
  3. public JsonResult Insert(Customer model)  
  4. {  
  5.     int result = 0;  
  6.     bool status = false;  
  7.     if (ModelState.IsValid)  
  8.     {  
  9.         try  
  10.         {  
  11.             object[] parameters = {  
  12.                 model.CustName,  
  13.                 model.CustEmail  
  14.             };  
  15.             result = objCust.Insert(parameters);  
  16.             if (result == 1)  
  17.             {  
  18.                 status = true;  
  19.             }  
  20.             return Json(new  
  21.             {  
  22.                 success = status  
  23.             });  
  24.         }  
  25.         catch  
  26.         {}  
  27.     }  
  28.     return Json(new  
  29.     {  
  30.         success = false,  
  31.             errors = ModelState.Keys.SelectMany(i => ModelState[i].Errors).Select(m => m.ErrorMessage).ToArray()  
  32.     });  
  33. }  
Update Records: Below code sample will update existing record details to database that is selected to update, which is also returning a JSON result of boolean data type.

If it’s true then it indicate that data updated to database successfully.
  1. // POST: Update Existing Customer  
  2. [HttpPost]  
  3. public JsonResult Update(Customer model)  
  4. {  
  5.     int result = 0;  
  6.     bool status = false;  
  7.     if (ModelState.IsValid)  
  8.     {  
  9.         try  
  10.         {  
  11.             object[] parameters = {  
  12.                 model.Id,  
  13.                 model.CustName,  
  14.                 model.CustEmail  
  15.             };  
  16.             result = objCust.Update(parameters);  
  17.             if (result == 1)  
  18.             {  
  19.                 status = true;  
  20.             }  
  21.             return Json(new  
  22.             {  
  23.                 success = status  
  24.             });  
  25.         }  
  26.         catch  
  27.         {}  
  28.     }  
  29.     return Json(new  
  30.     {  
  31.         success = false,  
  32.             errors = ModelState.Keys.SelectMany(i => ModelState[i].Errors).Select(m => m.ErrorMessage).ToArray()  
  33.     });  
  34. }  
Delete Records: Below code sample will delete existing record details to database that is selected to delete, which is also returning a JSON result of boolean data type.

If it’s true then it indicate that data deleted from database successfully.
  1. // DELETE: Delete Customer  
  2. [HttpDelete]  
  3. public JsonResult Delete(int id)  
  4. {  
  5.     int result = 0;  
  6.     bool status = false;  
  7.     try  
  8.     {  
  9.         object[] parameters = {  
  10.             id  
  11.         };  
  12.         result = objCust.Delete(parameters);  
  13.         if (result == 1)  
  14.         {  
  15.             status = true;  
  16.         }  
  17.     }  
  18.     catch  
  19.     {}  
  20.     return Json(new  
  21.     {  
  22.         success = status  
  23.     });  
  24. }  
We are done with our MVC Controller to perform CRUD operations on database. Now let’s move on to next part, the AngularJS part.

AngularJS(JavaScript) Controller
  1. angular.module('myFormApp', []).controller('CustomerController', function ($scope, $http, $location, $window)  
  2. {  
  3.     $scope.custModel = {};  
  4.     $scope.message = '';  
  5.     $scope.result = "color-default";  
  6.     $scope.isViewLoading = false;  
  7.     $scope.ListCustomer = null;  
  8.     getallData();  
  9.     //******=========Get All Customer=========******  
  10.     function getallData()  
  11.     {  
  12.         //debugger;  
  13.         $http.get('/Home/GetAllData').success(function (data, status, headers, config)  
  14.         {  
  15.             $scope.ListCustomer = data;  
  16.         }).error(function (data, status, headers, config)  
  17.         {  
  18.             $scope.errors = [];  
  19.             $scope.message = 'Unexpected Error while saving data!!';  
  20.             console.log($scope.message);  
  21.         });  
  22.     };  
  23.     //******=========Get Single Customer=========******  
  24.     $scope.getCustomer = function (custModel)  
  25.     {  
  26.         $http.get('/Home/GetbyID/' + custModel.Id).success(function (data, status, headers, config)  
  27.         {  
  28.             //debugger;  
  29.             $scope.custModel = data;  
  30.             getallData();  
  31.             console.log(data);  
  32.         }).error(function (data, status, headers, config)  
  33.         {  
  34.             $scope.errors = [];  
  35.             $scope.message = 'Unexpected Error while saving data!!';  
  36.             console.log($scope.message);  
  37.         });  
  38.     };  
  39.     //******=========Save Customer=========******  
  40.     $scope.saveCustomer = function ()  
  41.     {  
  42.         $scope.isViewLoading = true;  
  43.         $http(  
  44.         {  
  45.             method: 'POST',  
  46.             url: '/Home/Insert',  
  47.             data: $scope.custModel  
  48.         }).success(function (data, status, headers, config)  
  49.         {  
  50.             $scope.errors = [];  
  51.             if (data.success === true)  
  52.             {  
  53.                 $scope.message = 'Form data Saved!';  
  54.                 $scope.result = "color-green";  
  55.                 getallData();  
  56.                 $scope.custModel = {};  
  57.                 console.log(data);  
  58.             }  
  59.             else  
  60.             {  
  61.                 $scope.errors = data.errors;  
  62.             }  
  63.         }).error(function (data, status, headers, config)  
  64.         {  
  65.             $scope.errors = [];  
  66.             $scope.message = 'Unexpected Error while saving data!!';  
  67.             console.log($scope.message);  
  68.         });  
  69.         getallData();  
  70.         $scope.isViewLoading = false;  
  71.     };  
  72.     //******=========Edit Customer=========******  
  73.     $scope.updateCustomer = function ()  
  74.     {  
  75.         //debugger;  
  76.         $scope.isViewLoading = true;  
  77.         $http(  
  78.         {  
  79.             method: 'POST',  
  80.             url: '/Home/Update',  
  81.             data: $scope.custModel  
  82.         }).success(function (data, status, headers, config)  
  83.         {  
  84.             $scope.errors = [];  
  85.             if (data.success === true)  
  86.             {  
  87.                 $scope.custModel = null;  
  88.                 $scope.message = 'Form data Updated!';  
  89.                 $scope.result = "color-green";  
  90.                 getallData();  
  91.                 console.log(data);  
  92.             }  
  93.             else  
  94.             {  
  95.                 $scope.errors = data.errors;  
  96.             }  
  97.         }).error(function (data, status, headers, config)  
  98.         {  
  99.             $scope.errors = [];  
  100.             $scope.message = 'Unexpected Error while saving data!!';  
  101.             console.log($scope.message);  
  102.         });  
  103.         $scope.isViewLoading = false;  
  104.     };  
  105.     //******=========Delete Customer=========******  
  106.     $scope.deleteCustomer = function (custModel)  
  107.     {  
  108.         //debugger;  
  109.         varIsConf = confirm('You are about to delete ' + custModel.CustName + '. Are you sure?');  
  110.         if (IsConf)  
  111.         {  
  112.             $http.delete('/Home/Delete/' + custModel.Id).success(function (data, status, headers, config)  
  113.             {  
  114.                 $scope.errors = [];  
  115.                 if (data.success === true)  
  116.                 {  
  117.                     $scope.message = custModel.CustName + ' deleted from record!!';  
  118.                     $scope.result = "color-red";  
  119.                     getallData();  
  120.                     console.log(data);  
  121.                 }  
  122.                 else  
  123.                 {  
  124.                     $scope.errors = data.errors;  
  125.                 }  
  126.             }).error(function (data, status, headers, config)  
  127.             {  
  128.                 $scope.errors = [];  
  129.                 $scope.message = 'Unexpected Error while saving data!!';  
  130.                 console.log($scope.message);  
  131.             });  
  132.         }  
  133.     };  
  134. }).config(function ($locationProvider)  
  135. {  
  136.     $locationProvider.html5Mode(true);  
  137. });  
Code Explanation

$http is core AngularJS service that can communicate with the remote HTTP servers. HTTP methods that participate used to communicate:
  • $http.get: get data
  • $http.post: post new data
  • $http.put: update existing data
  • $http.delete: delete existing data

Know more about $http service here.

Get All Record: Using $http.get method we are retrieving all records from database.

  1. //******=========Get All Customer=========******  
  2. function getallData()  
  3. {  
  4.     //debugger;  
  5.     $http.get('/Home/GetAllData').success(function (data, status, headers, config)  
  6.     {  
  7.         $scope.ListCustomer = data;  
  8.     }).error(function (data, status, headers, config)  
  9.     {  
  10.         $scope.errors = [];  
  11.         $scope.message = 'Unexpected Error while saving data!!';  
  12.         console.log($scope.message);  
  13.     });  
  14. };  
Get Single Record: Here we are retrieving existing customer records from database. The $scope.getCustomer method is getting called while edit button is getting hit/click.
  1. //******=========Get Single Customer=========******  
  2. $scope.getCustomer = function (custModel)  
  3. {  
  4.     $http.get('/Home/GetbyID/' + custModel.Id).success(function (data, status, headers, config)  
  5.     {  
  6.         //debugger;  
  7.         $scope.custModel = data;  
  8.         getallData();  
  9.         console.log(data);  
  10.     }).error(function (data, status, headers, config)  
  11.     {  
  12.         $scope.errors = [];  
  13.         $scope.message = 'Unexpected Error while saving data!!';  
  14.         console.log($scope.message);  
  15.     });  
  16. };  
Using $http.get method we are retrieving selected customer record from database by passing the Customer ID to MVC Controller update method.

In return we are getting the query data and AngularJS $scope.custModel is binding the data to input model using ng-model, we know AngularJS support Two-way Data Binding.

Know more about Two-way Data Binding here.

Save Record: Here we are saving customer records. The $scope.saveCustomer method is getting called from UI when we submit the form with customer information by clicking the submit button.

Using $http.post we are passing the customer object to our MVC controller.
  1. //******=========Save Customer=========******  
  2. $scope.saveCustomer = function ()  
  3. {  
  4.     $scope.isViewLoading = true;  
  5.     $http(  
  6.     {  
  7.         method: 'POST',  
  8.         url: '/Home/Insert',  
  9.         data: $scope.custModel  
  10.     }).success(function (data, status, headers, config)  
  11.     {  
  12.         $scope.errors = [];  
  13.         if (data.success === true)  
  14.         {  
  15.             $scope.message = 'Form data Saved!';  
  16.             $scope.result = "color-green";  
  17.             getallData();  
  18.             $scope.custModel = {};  
  19.             console.log(data);  
  20.         }  
  21.         else  
  22.         {  
  23.             $scope.errors = data.errors;  
  24.         }  
  25.     }).error(function (data, status, headers, config)  
  26.     {  
  27.         $scope.errors = [];  
  28.         $scope.message = 'Unexpected Error while saving data!!';  
  29.         console.log($scope.message);  
  30.     });  
  31.     getallData();  
  32.     $scope.isViewLoading = false;  
  33. };  
The controller is doing the rest with a retun status of saved? or Not. After successful insertion we have reload (calling getallData() method again) the data table.

Edit Record: Here we are updating existing customer records to the database. The $scope.updateCustomer method is getting called while update button is getting hit/click.

Like save record, same thing also happening here. The main difference in saving and updating is the Cutomer ID. This time we are passing Customer ID with customer object which is getting from a hidden input field.
  1. <input type="hidden" ng-model="custModel.Id" name="cid" />  
Using $http.post we are passing the customer object to our MVC controller.
  1. //******=========Edit Customer=========******  
  2. $scope.updateCustomer = function ()  
  3. {  
  4.     //debugger;  
  5.     $scope.isViewLoading = true;  
  6.     $http(  
  7.     {  
  8.         method: 'POST',  
  9.         url: '/Home/Update',  
  10.         data: $scope.custModel  
  11.     }).success(function (data, status, headers, config)  
  12.     {  
  13.         $scope.errors = [];  
  14.         if (data.success === true)  
  15.         {  
  16.             $scope.custModel = null;  
  17.             $scope.message = 'Form data Updated!';  
  18.             $scope.result = "color-green";  
  19.             getallData();  
  20.             console.log(data);  
  21.         }  
  22.         else  
  23.         {  
  24.             $scope.errors = data.errors;  
  25.         }  
  26.     }).error(function (data, status, headers, config)  
  27.     {  
  28.         $scope.errors = [];  
  29.         $scope.message = 'Unexpected Error while saving data!!';  
  30.         console.log($scope.message);  
  31.     });  
  32.     $scope.isViewLoading = false;  
  33. };  
The controller is doing the rest with a retun status of updated? or Not. After successful updating we have reload(calling getallData() method again) the data table.

Delete Record: Here we are deleting existing customer records from database. The $scope.deleteCustomer method is getting called while delete button is getting hit/click.
  1. //******=========Delete Customer=========******  
  2. $scope.deleteCustomer = function (custModel)  
  3. {  
  4.     //debugger;  
  5.     varIsConf = confirm('You are about to delete ' + custModel.CustName + '. Are you sure?');  
  6.     if (IsConf)  
  7.     {  
  8.         $http.delete('/Home/Delete/' + custModel.Id).success(function (data, status, headers, config)  
  9.         {  
  10.             $scope.errors = [];  
  11.             if (data.success === true)  
  12.             {  
  13.                 $scope.message = custModel.CustName + ' deleted from record!!';  
  14.                 $scope.result = "color-red";  
  15.                 getallData();  
  16.                 console.log(data);  
  17.             }  
  18.             else  
  19.             {  
  20.                 $scope.errors = data.errors;  
  21.             }  
  22.         }).error(function (data, status, headers, config)  
  23.         {  
  24.             $scope.errors = [];  
  25.             $scope.message = 'Unexpected Error while saving data!!';  
  26.             console.log($scope.message);  
  27.         });  
  28.     }  
  29. };  
Let’s get into UI/View section. Here’s the Index view where we perform CRUD operations graphically.

Html View
  1. @{  
  2. ViewBag.Title = "Index";  
  3. }  
  4.   
  5.   
  6. <h2>Create Customer</h2>  
  7. <div id="content"ng-controller="CustomerController">  
  8.     <span ng-show="isViewLoading"class="viewLoading">  
  9.         <img src="~/Content/images/ng-loader.gif"/> loading...  
  10.   
  11.     </span>  
  12.     <div ng-class="result">{{message}}  
  13.     </div>  
  14.     <hr/>  
  15.     <form name="frmCustomer"novalidate>  
  16.         <div>  
  17.             <input type="hidden"ng-model="custModel.Id"name="cid"/>  
  18.         </div>  
  19.         <div>  
  20.             <label for="email">Customer Name  
  21.             </label>  
  22.             <input type="text"ng-model="custModel.CustName"name="cname"placeholder=""requiredng-minlength="4"ng-maxlength="14"/>  
  23.             <span class="error"ng-show="(frmCustomer.$dirty||submitted)&&frmCustomer.cname.$error.required">Customer name is Required  
  24.             </span>  
  25.             <span class="error"ng-show="frmCustomer.$dirty&&frmCustomer.cname.$error.minlength">Minimum length required is 5  
  26.             </span>  
  27.             <span class="error"ng-show="frmCustomer.$dirty&&frmCustomer.cname.$error.maxlength">Minimum length required is 15  
  28.             </span>  
  29.         </div>  
  30.         <div>  
  31.             <label for="email">E-mail address  
  32.             </label>  
  33.             <input type="email"ng-model="custModel.CustEmail"name="email"placeholder=""required/>  
  34.             <span class="error"ng-show="(frmCustomer.$dirty||submitted)&&frmCustomer.email.$error.required">EmailId is Required!  
  35.             </span>  
  36.             <span class="error"ng-show="(frmCustomer.$dirty||submitted)&&frmCustomer.$error.email">Invalid EmailId!  
  37.             </span>  
  38.         </div>  
  39.         <div class="btn">  
  40.             <input type="submit"value="Save"ng-click="saveCustomer()"ng-disabled="frmCustomer.$invalid">  
  41.                 <input type="submit"value="Update"ng-click="updateCustomer()"ng-disabled="frmCustomer.$invalid">  
  42.                 </div>  
  43.             </form>  
  44.             <hr/>  
  45.             <h2>All Customers</h2>  
  46.             <table class="table table-striped">  
  47.                 <trng-repeat="custModelinListCustomer">  
  48.                     <td>{{custModel.Id}}</td>  
  49.                     <td>{{custModel.CustName}}</td>  
  50.                     <td>{{custModel.CustEmail}}</td>  
  51.                     <td>  
  52.                         <a href="#"ng-click="getCustomer(custModel)"title="Edit Record">  
  53.                             <imgsrc="~/Content/images/edit.png"/>  
  54.                         </a>  
  55.                         <a href="#"ng-click="deleteCustomer(custModel)"title="Delete Record">  
  56.                             <imgsrc="~/Content/images/erase.png"/>  
  57.                         </a>  
  58.                     </td>  
  59.                 </tr>  
  60.             </table>  
  61.         </div>  
  62.   
  63. @section JavaScript{  
  64.   
  65.         <script src="~/Scripts/angular.js">  
  66.         </script>  
  67.         <script src="~/ScriptsNg/CustomerController.js">  
  68.         </script>  
  69. }  
Code Explanation

Below code sample is a table with repeating table row(<tr>). Here, ng-repeat is displaying single record(custModel ) with it’s template once per record from ListCustomer, or simply working as a repeater of table row.

Know more about ng-repeat here.
  1. <table class="table table-striped">  
  2.     <trng-repeat="custModelinListCustomer">  
  3.         <td>{{custModel.Id}}</td>  
  4.         <td>{{custModel.CustName}}</td>  
  5.         <td>{{custModel.CustEmail}}</td>  
  6.         <td>  
  7.             <ahref="#" ng-click="getCustomer(custModel)" title="Edit Record">  
  8.                 <img src="~/Content/images/edit.png" /> </a>  
  9.                 <a href="#" ng-click="deleteCustomer(custModel)" title="Delete Record">  
  10.                     <imgsrc="~/Content/images/erase.png" /> </a>  
  11.         </td>   
  12.     </tr>  
  13. </table>  
We are almost done. Let’s style our UI with CSS, below is css that we used to style the UI.

Form Style
  1. #content label  
  2. {  
  3.     width150 px;  
  4. }.btn  
  5. {  
  6.     margin - left: 140 px;  
  7. }#conten tinput[type = submit]  
  8.     {  
  9.         width85 px;  
  10.         padding5 px15px;  
  11.         background#ff6a00;  
  12.         border0 none;  
  13.         cursorpointer;  
  14.         color#fff;  
  15.     }.error  
  16.     {  
  17.         colorred;  
  18.     }.color -  
  19.     default  
  20.     {  
  21.         color#000;  
  22. }  
  23.   
  24. .color-red {  
  25. colorred;  
  26. }  
  27.   
  28. .color-green {  
  29. colorgreen;  
  30. }  
  31.   
  32. # contentinput.ng - dirty.ng - invalid  
  33. {  
  34.     border1 pxsolidred;  
  35.     background - colorrgb(255244244);  
  36. }  
  37. [ng\: cloak],  
  38. [ng - cloak],  
  39. [data - ng - cloak],  
  40. [x - ng - cloak],  
  41. .ng - cloak,  
  42. .x - ng - cloak  
  43. {  
  44.     displaynone!important;  
  45. }  
Hide Directive Flash (ng-cloak)

While loading our page you may noticed that Angular html template are visible/flash. It happened while the browser in its compilation process of Angular html template, usually it flash while the page is loading. Which can hide using “ng-cloak/data-ng-cloak” directive.

Know more about ng-cloak here.

We also need to add css class in our application start point.<body ng-app="myFormApp" class="ng-cloak">. Below is the css class of using ng-cloak.
  1. [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {  
  2.    display: none!important;  
  3. }  
Let’s put a breakpoint on Updater() method in HomeController and run it, after submitting the form it’ll hit the breakpoint.

Controller

In debug mode we can see the model is populated with form data. We can also debug using browser by putting debugger in our script.
  1. $scope.updateCustomer = function () {  
  2.    debugger;  
  3. };  
debugger

In debug mode in our browser we can see the $scope.custModel is populated with form data, which is going to update the selected record in database.

Output

Output

[Browser: Inspect > Console]

Inspect

[Browser: Inspect > Network]

Network

Hope that this will help you to learn AngularJS.

Points of Interest

In the next part we will make a Single Page Application(SPA) based on this Application to maintain the flow, and focus on AngularJS Routing.