AngularJS CRUD (Create Read Update Delete) Operation Using MVC

Since we are using EntityFramwork for CRUD operation, so, first, create a table, given below-

table

Step 1. Create MVC Application

  • Open Visual Studio

  • File - New - Project…

  • Select ASP.NET MVC4/5 Web Application.

  • Enter the name of Application as "AngularWithMvc".

  • Click OK.

Step 2. Create the Model

As we know, we will use the EntityFramework, so we will use the .edmx model and will use its entity(Table) as a model. So,

  1. Right click on the Models folder and go to Add. Select Add New Item, given below-

    web

  2. Now, select Data tab from Side menu, choose entity data model and type the name of entity data model, as given below-

    entity data model

  3. Create a controller with the name of “ StudentController”, as given below-

    StudentController

  4. This was the process to create an MVC Application and Entity data model integration. Now, we are going to create a model, Controller and Service to perform the CRUD operation. Thus, create a folder at the root with the name of “AngularScript” and add the “angular.min.js” from the link, given below-

  5. http://ajax.googleapis.com/ajax/libs/angularjs/1.2.12/angular.min.js

    Now, create three JavaScript files with the name of “StudentModel”, “StudentService” and “StudentController”, as given below-

    JavaScript file

Open StudentController.cs (MVC Controller). Create a View with the name of Index and write the code, given below-

Index.cshtml

  1. @{  
  2.   
  3. ViewBag.Title = "Index";  
  4.   
  5. Layout = "~/Views/Shared/_Layout.cshtml";  
  6.   
  7.   
  8. }  
  9.   
  10.   
  11.   
  12. <h2>Student Details :</h2>  
  13. <div ng-controller="stuCntr">  
  14.     <script src="~/scripts/bootstrap.min.js"></script>  
  15.     <script src="~/scripts/jquery-1.10.2.min.js"></script>  
  16.     <input type="submit" value="Add Student" ng-click="AddNewStudent()" />  
  17.     <div id="dvStudnetDetails">  
  18.         <table cellpadding="12" class="table table-bordered table-hover">  
  19.             <tr>  
  20.                 <td>  
  21.                     <b>Id</b>  
  22.                 </td>  
  23.                 <td>  
  24.                     <b>Student Name</b>  
  25.                 </td>  
  26.                 <td>  
  27.                     <b>Address</b>  
  28.                 </td>  
  29.                 <td>  
  30.                     <b>Email</b>  
  31.                 </td>  
  32.                 <td>  
  33.                     <b>Manage</b>  
  34.                 </td>  
  35.             </tr>  
  36.             <tr ng-repeat="stu in students">  
  37.                 <td ng-show="aa">  
  38.   
  39. {{stu.Id}}  
  40.   
  41.   
  42. </td>  
  43.                 <td>  
  44.   
  45. {{$index+1}}  
  46.   
  47.   
  48. </td>  
  49.                 <td ng-show="a">  
  50.                     <input type="text" ng-model="stu.StudentName" />  
  51.                 </td>  
  52.                 <td ng-hide="a">  
  53.   
  54. {{stu.StudentName}}  
  55.   
  56.   
  57. </td>  
  58.                 <td ng-show="a">  
  59.                     <input type="text" ng-model="stu.StudentAddress" />  
  60.                 </td>  
  61.                 <td ng-hide="a">  
  62.   
  63. {{stu.StudentAddress}}  
  64.   
  65.   
  66. </td>  
  67.                 <td ng-show="a">  
  68.                     <input type="text" ng-model="stu.StudentEmail" />  
  69.                 </td>  
  70.                 <td ng-hide="a">  
  71.   
  72. {{stu.StudentEmail}}  
  73.   
  74.   
  75. </td>  
  76.                 <td>  
  77.                     <span ng-hide="a" ng-click="a=!a">Edit</span>  
  78.                     <span ng-show="a" ng-click="a=!a">Cancel</span>  
  79.                     <span ng-show="a" ng-click="UpdateStudent(stu)">Update</span>  
  80.                     <span ng-click="deleteStudent(stu,$index)">Delete</span>  
  81.                 </td>  
  82.             </tr>  
  83.         </table>  
  84.     </div>  
  85.     <div id="dvAddStudnet" ng-show="dvStudent">  
  86.         <p class="dvTask">{{Action}} New Student</p>  
  87.         <table>  
  88.             <tr>  
  89.                 <td>Name : </td>  
  90.                 <td>  
  91.                     <input type="text" id="txtName" ng-model="student.StudentName" />  
  92.                 </td>  
  93.             </tr>  
  94.             <tr>  
  95.                 <td>Email : </td>  
  96.                 <td>  
  97.                     <input type="text" id="txtEmail" ng-model="student.StudentEmail" />  
  98.                 </td>  
  99.             </tr>  
  100.             <tr>  
  101.                 <td>Address : </td>  
  102.                 <td>  
  103.                     <input type="text" id="txtAddress" ng-model="student.StudentAddress" />  
  104.                 </td>  
  105.             </tr>  
  106.         </table>  
  107.         <input type="submit" value="Submit" ng-click="AddStudnet(student)" />  
  108.     </div>  
  109. </div>  

In View, given above, I have created HTML table and bound a data field, using AngularJS directives (ng-model, ng-controller, ng-repeat etc.) and there are also a code form to add new student records (See in dvAddStudnet div). This view contains a controller section only. There are no ng-App in this view. We have written the ng-app directives in layout, which renders all the view, as given below-

code

_Layout.cshtml

  1. <!DOCTYPE html>  
  2. <html ng-app="StudnetApp">  
  3.   
  4. <head>  
  5.     <meta charset="utf-8" />  
  6.     <meta name="viewport" content="width=device-width, initial-scale=1.0">  
  7.     <title>@ViewBag.Title - Angular Js with MVC Demo</title>  
  8.     <link href="~/Content/Site.css" rel="stylesheet" type="text/css" />  
  9.     <link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />  
  10.     <script src="~/Scripts/modernizr-2.6.2.js"></script> @*Angular liabrary and js used in Application*@  
  11.     <script src="~/AngularScricpt/angular.min.js"></script>  
  12.     <script src="~/AngularScricpt/StudentModel.js"></script>  
  13.     <script src="~/AngularScricpt/StudentService.js"></script>  
  14.     <script src="~/AngularScricpt/Studnetcontroller.js"></script>  
  15. </head>  
  16.   
  17. <body>  
  18.     <div class="navbar navbar-inverse navbar-fixed-top">  
  19.         <div class="container">  
  20.             <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">  
  21.   
  22. <span class="icon-bar"></span>  
  23.   
  24. <span class="icon-bar"></span>  
  25.   
  26. <span class="icon-bar"></span>  
  27.   
  28. </button> @Html.ActionLink("AngularJs Demo", "Index", "Student", new { area = "" }, new { @class = "navbar-brand" }) </div>  
  29.             <div class="navbar-collapse collapse">  
  30.                 <ul class="nav navbar-nav"> </ul>  
  31.             </div>  
  32.         </div>  
  33.     </div>  
  34.     <div class="container body-content"> @RenderBody()  
  35.         <hr />  
  36.         <footer>  
  37.             <p>© @DateTime.Now.Year - AngularJs with MVC demo</p>  
  38.         </footer>  
  39.     </div>  
  40.     <script src="~/Scripts/jquery-1.10.2.min.js"></script>  
  41.     <script src="~/Scripts/bootstrap.min.js"></script>  
  42. </body>  
  43.   </html>  

Now, open StudentModel.js (in AngularScript folder) and assign the app's name, which you have given in layout page. It is very easy, as you need to just open studentmodel.js and type the name of app, given below-

StudentModel.js

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

We are only assigning the module name in this file.

Now, open StudnetController.js and write the code, given below-

StudentController.js

  1. app.controller("stuCntr"function($scope, StudentService) {  
  2.     $scope.dvStudent = false;  
  3.     GetStudentList();  
  4.     $scope.students = [];  
  5.     //To Get All Records  
  6.     function GetStudentList() {  
  7.         StudentService.getAllStudents().success(function(stu) {  
  8.             $scope.students = stu;  
  9.         }).error(function() {  
  10.             alert('Error in getting records');  
  11.         });  
  12.     }  
  13.     // To display Add div  
  14.     $scope.AddNewStudent = function() {  
  15.             $scope.Action = "Add";  
  16.             $scope.dvStudent = true;  
  17.         }  
  18.         // Adding New student record  
  19.     $scope.AddStudnet = function(student) {  
  20.             StudentService.AddNewStudent(student).success(function(msg) {  
  21.                 $scope.students.push(msg)  
  22.                 $scope.dvAddStudnet = false;  
  23.             }, function() {  
  24.                 alert('Error in adding record');  
  25.             });  
  26.         }  
  27.         // Deleting record.  
  28.     $scope.deleteStudent = function(stu, index) {  
  29.             var retval = StudentService.deleteStudent(stu.Id).success(function(msg) {  
  30.                 $scope.students.splice(index, 1);  
  31.                 // alert('Student has been deleted successfully.');  
  32.             }).error(function() {  
  33.                 alert('Oops! something went wrong.');  
  34.             });  
  35.         }  
  36.         // Updateing Records  
  37.     $scope.UpdateStudent = function(tbl_Student) {  
  38.         var RetValData = StudentService.UpdateStudent(tbl_Student);  
  39.         getData.then(function(tbl_Student) {  
  40.             Id: $scope.Id;  
  41.             StudentName: $scope.studentName;  
  42.             StudentAddress: $scope.StudentAddress;  
  43.             StudentEmail: $scope.StudentEmail;  
  44.         }, function() {  
  45.             alert('Error in getting records');  
  46.         });  
  47.     }  
  48. });  

In the code, given above, we create a controller and written all CRUD operation code. We also assigned Services, which will invoke the MVC controller to perform the action, as required. (See the controller, Service and all function in the image, given below)-

code

Now, open StudentService.js file and write the code, given below. Here, View calls the controller, controller calls the Service and Service calls the MVC controller action.

StudentService.js

  1. app.service("StudentService"function($http) {  
  2.     //get All Eployee  
  3.     this.getAllStudents = function() {  
  4.         return $http.get("Student/GetStudentList");  
  5.     };  
  6.     // Adding Record  
  7.     this.AddNewStudent = function(tbl_Student) {  
  8.             return $http({  
  9.                 method: "post",  
  10.                 url: "Student/AddStudent",  
  11.                 data: JSON.stringify(tbl_Student),  
  12.                 dataType: "json"  
  13.             });  
  14.         }  
  15.         // Updating record  
  16.     this.UpdateStudent = function(tbl_Student) {  
  17.             return $http({  
  18.                 method: "post",  
  19.                 url: "Student/UpdateStudent",  
  20.                 data: JSON.stringify(tbl_Student),  
  21.                 dataType: "json"  
  22.             });  
  23.         }  
  24.         // Deleting records  
  25.     this.deleteStudent = function(Id) {  
  26.         return $http.post('Student/DeleteStudent/' + Id)  
  27.     }  
  28. });  

Now, open StudentController.cs (MVC controller) and write the code, given below. The code, given below, has all the action from CRUD operation-

StudentController.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using AngularWithMvc.Models;  
  7. namespace AngularWithMvc.Controllers   
  8. {  
  9.     public class StudentController: Controller {  
  10.         // GET: Student  
  11.         public ActionResult Index() {  
  12.                 return View();  
  13.             }  
  14.             [HttpPost]  
  15.         public JsonResult AddStudent(tbl_Student stu) {  
  16.                 if (stu != null) {  
  17.                     using(TestDBEntities dbContext = new TestDBEntities()) {  
  18.                         dbContext.tbl_Student.Add(stu);  
  19.                         dbContext.SaveChanges();  
  20.                         return Json(stu, JsonRequestBehavior.AllowGet);  
  21.                     }  
  22.                 } else {  
  23.                     return Json("Some Error Occured");  
  24.                 }  
  25.             }  
  26.             [HttpPost]  
  27.         public string UpdateStudent(tbl_Student stu) {  
  28.             if (stu != null) {  
  29.                 using(TestDBEntities dbContext = new TestDBEntities()) {  
  30.                     tbl_Student lstStudent = dbContext.tbl_Student.Where(x => x.Id == stu.Id).FirstOrDefault();  
  31.                     lstStudent.StudentName = stu.StudentName;  
  32.                     lstStudent.StudentAddress = stu.StudentAddress;  
  33.                     lstStudent.StudentEmail = stu.StudentEmail;  
  34.                     dbContext.SaveChanges();  
  35.                     return "Student Updated";  
  36.                 }  
  37.             } else {  
  38.                 return "Oops! something went wrong.";  
  39.             }  
  40.         }  
  41.         public JsonResult GetStudentList() {  
  42.                 using(TestDBEntities dbContext = new TestDBEntities()) {  
  43.                     List < tbl_Student > studentList = dbContext.tbl_Student.ToList();  
  44.                     return Json(studentList, JsonRequestBehavior.AllowGet);  
  45.                 }  
  46.             }  
  47.             [HttpPost]  
  48.         public string DeleteStudent(int Id) {  
  49.             if (Id != 0) {  
  50.                 using(TestDBEntities dataContext = new TestDBEntities()) {  
  51.                     // int id = Convert.ToInt32(Id);  
  52.                     var lstStud = dataContext.tbl_Student.Where(x => x.Id == Id).FirstOrDefault();  
  53.                     dataContext.tbl_Student.Remove(lstStud);  
  54.                     dataContext.SaveChanges();  
  55.                     return "Student has been deleted succhessfully.";  
  56.                 }  
  57.             } else {  
  58.                 return " Oops! Error occered.";  
  59.             }  
  60.         }  
  61.     }  
  62. }  

Now, press F5 to run the code. I hope, your Browser will display the screen, as shown below-

output