Thursday, January 16, 2020

angularjs-crud operation using asp net mvc

First, we create an MVC project. Go to File-> New-> Project and select “ASP.NET Web Application”.

Now, select MVC template for the project.

In Solution Explorer window, we can see the structure of our project.

Now, we add the model classes in our project. We have an Employee table which we will use in our project and implement the CRUD operation on.

CREATE TABLE [dbo].[Employee](  
[Emp_Id] [int] IDENTITY(1,1) NOT NULL,  
[Emp_Name] [varchar](max) NULL,  
[Emp_City] [varchar](max) NULL,  
[Emp_Age] [int] NULL,  
CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED   
(  
[Emp_Id] ASC  
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]  
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]  
  
GO  




 

For database CRUD operation, we will use the Entity Framework Data First approach. For this, right click on “Model” folder and click on “New Item” option.


Now, select “ADO.NET Entity Data Model” and name it as “EmployeeModel”.

Establish a connection with “SQL Server Database” Engine.


Select Employee table Entity Data Model Wizard and click on Finish button.

Now, go to your project’s Model folder where you can see that Employee Model class has been created. So, you have successfully created a connection with database.


After this, we download and install the AngularJS package. Right click on Project Name and select “Manage NuGet Packages” option and download the AngularJS packages.


In Scripts folder, you can find that AngularJS files have been installed successfully.

Now, we create the Employee Controller. So, right click on Controller Folder and create an empty Controller.

Now, copy and paste the following code into your Employee Controller section.

  1. using AngularCRUD.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.Mvc;  
  7. namespace AngularCRUD.Controllers {  
  8.     public class EmployeeController: Controller {  
  9.         // GET: Employee  
  10.         public ActionResult Index() {  
  11.                 return View();  
  12.             }  
  13.             /// <summary>  
  14.             ///   
  15.             /// Get All Employee  
  16.             /// </summary>  
  17.             /// <returns></returns>  
  18.         public JsonResult Get_AllEmployee() {  
  19.                 using(DemoEntities Obj = new DemoEntities()) {  
  20.                     List < Employee > Emp = Obj.Employees.ToList();  
  21.                     return Json(Emp, JsonRequestBehavior.AllowGet);  
  22.                 }  
  23.             }  
  24.             /// <summary>  
  25.             /// Get Employee With Id  
  26.             /// </summary>  
  27.             /// <param name="Id"></param>  
  28.             /// <returns></returns>  
  29.         public JsonResult Get_EmployeeById(string Id) {  
  30.                 using(DemoEntities Obj = new DemoEntities()) {  
  31.                     int EmpId = int.Parse(Id);  
  32.                     return Json(Obj.Employees.Find(EmpId), JsonRequestBehavior.AllowGet);  
  33.                 }  
  34.             }  
  35.             /// <summary>  
  36.             /// Insert New Employee  
  37.             /// </summary>  
  38.             /// <param name="Employe"></param>  
  39.             /// <returns></returns>  
  40.         public string Insert_Employee(Employee Employe) {  
  41.                 if (Employe != null) {  
  42.                     using(DemoEntities Obj = new DemoEntities()) {  
  43.                         Obj.Employees.Add(Employe);  
  44.                         Obj.SaveChanges();  
  45.                         return "Employee Added Successfully";  
  46.                     }  
  47.                 } else {  
  48.                     return "Employee Not Inserted! Try Again";  
  49.                 }  
  50.             }  
  51.             /// <summary>  
  52.             /// Delete Employee Information  
  53.             /// </summary>  
  54.             /// <param name="Emp"></param>  
  55.             /// <returns></returns>  
  56.         public string Delete_Employee(Employee Emp) {  
  57.                 if (Emp != null) {  
  58.                     using(DemoEntities Obj = new DemoEntities()) {  
  59.                         var Emp_ = Obj.Entry(Emp);  
  60.                         if (Emp_.State == System.Data.Entity.EntityState.Detached) {  
  61.                             Obj.Employees.Attach(Emp);  
  62.                             Obj.Employees.Remove(Emp);  
  63.                         }  
  64.                         Obj.SaveChanges();  
  65.                         return "Employee Deleted Successfully";  
  66.                     }  
  67.                 } else {  
  68.                     return "Employee Not Deleted! Try Again";  
  69.                 }  
  70.             }  
  71.             /// <summary>  
  72.             /// Update Employee Information  
  73.             /// </summary>  
  74.             /// <param name="Emp"></param>  
  75.             /// <returns></returns>  
  76.         public string Update_Employee(Employee Emp) {  
  77.             if (Emp != null) {  
  78.                 using(DemoEntities Obj = new DemoEntities()) {  
  79.                     var Emp_ = Obj.Entry(Emp);  
  80.                     Employee EmpObj = Obj.Employees.Where(x => x.Emp_Id == Emp.Emp_Id).FirstOrDefault();  
  81.                     EmpObj.Emp_Age = Emp.Emp_Age;  
  82.                     EmpObj.Emp_City = Emp.Emp_City;  
  83.                     EmpObj.Emp_Name = Emp.Emp_Name;  
  84.                     Obj.SaveChanges();  
  85.                     return "Employee Updated Successfully";  
  86.                 }  
  87.             } else {  
  88.                 return "Employee Not Updated! Try Again";  
  89.             }  
  90.         }  
  91.     }  
  92. }  

After creating the Controller, now, we create a View. Right click on Index method and create an Empty View.



Paste the following code into the Index View:

  1. @{  
  2. ViewBag.Title = "Index";  
  3. }  
  4.   
  5. <style>  
  6. .btn-space {  
  7. margin-left: -5%;  
  8. background-color: cornflowerblue;  
  9. font-size: large;  
  10. }  
  11. </style>  
  12. <h2>Index</h2>  
  13. <div ng-app="myApp">  
  14.     <div ng-controller="myCtrl" ng-init="GetAllData()" class="divList">  
  15.         <p class="divHead">List of Employee</p>  
  16.         <table cellpadding="12" class="table table-bordered table-hover">  
  17.             <tr>  
  18.                 <td>  
  19.                     <b>ID</b>  
  20.                 </td>  
  21.                 <td>  
  22.                     <b>Name</b>  
  23.                 </td>  
  24.                 <td>  
  25.                     <b>City</b>  
  26.                 </td>  
  27.                 <td>  
  28.                     <b>Age</b>  
  29.                 </td>  
  30.                 <td>  
  31.                     <b>Actions</b>  
  32.                 </td>  
  33.             </tr>  
  34.             <tr ng-repeat="Emp in employees">  
  35.                 <td>  
  36. {{Emp.Emp_Id}}  
  37. </td>  
  38.                 <td>  
  39. {{Emp.Emp_Name}}  
  40. </td>  
  41.                 <td>  
  42. {{Emp.Emp_City}}  
  43. </td>  
  44.                 <td>  
  45. {{Emp.Emp_Age}}  
  46. </td>  
  47.                 <td>  
  48.                     <input type="button" class="btn btn-warning" value="Update" ng-click="UpdateEmp(Emp)" />  
  49.                     <input type="button" class="btn btn-danger" value="Delete" ng-click="DeleteEmp(Emp)" />  
  50.                 </td>  
  51.             </tr>  
  52.         </table>  
  53.         <div class="form-horizontal" role="form">  
  54.             <div class="container">  
  55.                 <div class="row">  
  56.                     <h2>  
  57.                         <span id="spn">Add New Employee</span>  
  58.                     </h2>  
  59.                 </div>  
  60.                 <div class="row">  
  61.                     <div class="col-sm-6 col-lg-4">  
  62.                         <div class="form-group">  
  63.                             <label class="col-md-4 control-label">Name:</label>  
  64.                             <div class="col-md-8">  
  65.                                 <input type="text" class="form-control" id="inputEmail" placeholder="Name" ng-model="EmpName">  
  66.                                 </div>  
  67.                             </div>  
  68.                         </div>  
  69.                         <div class="col-sm-6 col-lg-4">  
  70.                             <div class="form-group">  
  71.                                 <label class="col-md-4 control-label">City:</label>  
  72.                                 <div class="col-md-8">  
  73.                                     <input type="text" class="form-control" id="inputPassword" placeholder="City" ng-model="EmpCity">  
  74.                                     </div>  
  75.                                 </div>  
  76.                             </div>  
  77.                             <div class="col-sm-6 col-lg-4">  
  78.                                 <div class="form-group">  
  79.                                     <label class="col-md-4 control-label">Age:</label>  
  80.                                     <div class="col-md-8">  
  81.                                         <input type="text" class="form-control" id="inputLabel3" placeholder="Age" ng-model="EmpAge">  
  82.                                         </div>  
  83.                                     </div>  
  84.                                 </div>  
  85.                             </div>  
  86.                             <div class="row">  
  87.                                 <div class="col-sm-6 col-lg-4">  
  88.                                     <input type="button" id="btnSave" class="form-control btn-space" value="Submit" ng-click="InsertData()" />  
  89.                                 </div>  
  90.                             </div>  
  91.                         </div>  
  92.                     </div>  
  93.                 </div>  
  94. @Html.Hidden("EmpID_")  
  95.   
  96.             </div>  

For CRUD operations in AngularJS, we create a JavaScript file, write the code into that file, and implement this file into our Index View.

First, create a JavaScript file and copy the following code.


JavaScript code

  1. var app = angular.module("myApp", []);  
  2. app.controller("myCtrl"function($scope, $http) {  
  3.     debugger;  
  4.     $scope.InsertData = function() {  
  5.         var Action = document.getElementById("btnSave").getAttribute("value");  
  6.         if (Action == "Submit") {  
  7.             $scope.Employe = {};  
  8.             $scope.Employe.Emp_Name = $scope.EmpName;  
  9.             $scope.Employe.Emp_City = $scope.EmpCity;  
  10.             $scope.Employe.Emp_Age = $scope.EmpAge;  
  11.             $http({  
  12.                 method: "post",  
  13.                 url: "http://localhost:39209/Employee/Insert_Employee",  
  14.                 datatype: "json",  
  15.                 data: JSON.stringify($scope.Employe)  
  16.             }).then(function(response) {  
  17.                 alert(response.data);  
  18.                 $scope.GetAllData();  
  19.                 $scope.EmpName = "";  
  20.                 $scope.EmpCity = "";  
  21.                 $scope.EmpAge = "";  
  22.             })  
  23.         } else {  
  24.             $scope.Employe = {};  
  25.             $scope.Employe.Emp_Name = $scope.EmpName;  
  26.             $scope.Employe.Emp_City = $scope.EmpCity;  
  27.             $scope.Employe.Emp_Age = $scope.EmpAge;  
  28.             $scope.Employe.Emp_Id = document.getElementById("EmpID_").value;  
  29.             $http({  
  30.                 method: "post",  
  31.                 url: "http://localhost:39209/Employee/Update_Employee",  
  32.                 datatype: "json",  
  33.                 data: JSON.stringify($scope.Employe)  
  34.             }).then(function(response) {  
  35.                 alert(response.data);  
  36.                 $scope.GetAllData();  
  37.                 $scope.EmpName = "";  
  38.                 $scope.EmpCity = "";  
  39.                 $scope.EmpAge = "";  
  40.                 document.getElementById("btnSave").setAttribute("value""Submit");  
  41.                 document.getElementById("btnSave").style.backgroundColor = "cornflowerblue";  
  42.                 document.getElementById("spn").innerHTML = "Add New Employee";  
  43.             })  
  44.         }  
  45.     }  
  46.     $scope.GetAllData = function() {  
  47.         $http({  
  48.             method: "get",  
  49.             url: "http://localhost:39209/Employee/Get_AllEmployee"  
  50.         }).then(function(response) {  
  51.             $scope.employees = response.data;  
  52.         }, function() {  
  53.             alert("Error Occur");  
  54.         })  
  55.     };  
  56.     $scope.DeleteEmp = function(Emp) {  
  57.         $http({  
  58.             method: "post",  
  59.             url: "http://localhost:39209/Employee/Delete_Employee",  
  60.             datatype: "json",  
  61.             data: JSON.stringify(Emp)  
  62.         }).then(function(response) {  
  63.             alert(response.data);  
  64.             $scope.GetAllData();  
  65.         })  
  66.     };  
  67.     $scope.UpdateEmp = function(Emp) {  
  68.         document.getElementById("EmpID_").value = Emp.Emp_Id;  
  69.         $scope.EmpName = Emp.Emp_Name;  
  70.         $scope.EmpCity = Emp.Emp_City;  
  71.         $scope.EmpAge = Emp.Emp_Age;  
  72.         document.getElementById("btnSave").setAttribute("value""Update");  
  73.         document.getElementById("btnSave").style.backgroundColor = "Yellow";  
  74.         document.getElementById("spn").innerHTML = "Update Employee Information";  
  75.     }  
  76. })  

Now, provide the references of AngularJS and AngularCode file that we created into Index View.


Now, I think our project is ready to work. So, let’s run the application. Press F5 and you can see that following screen will be visible on your browser.