CRUD Operations in MVC with AngularJs.
In this Tutorial, I’ll show you How to perform CRUD Operations in MVC with AngularJs.AngularJs Is Javascript framework to SPA (Single Page Application).
There are any Advantage of using AngularJs.
In this Tutorial I have Used Employee table to Perform Create, Read, Update and Delete (CRUD Operations).
Let’s Begin with creating an MVC application.
Open Visual studio .
File => New => Project

Click Ok. Then a new popup window will open.

Now create a Employee model class to perform CRUD Operations.
01
02
03
04
05
06
07
08
09
10
11
12
13
| using System.ComponentModel.DataAnnotations; namespace CrudInAj.Models { public class Employee { [Key] public int Id { get ; set ; } public string Name { get ; set ; } public string Email { get ; set ; } public int Age { get ; set ; } } } |
1
2
3
4
5
6
7
8
| using System.Data.Entity; namespace CrudInAj.Models { public class DemoContext:DbContext { public DbSet<Employee> employee { get ; set ; } } } |
Now modify your connectionstring according to your context class.
1
2
3
| < connectionStrings > < add name = "DemoContext" providerName = "System.Data.SqlClient" connectionString = "Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-CrudInAj-20141222205150;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-CrudInAj-20141222205150.mdf" /> </ connectionStrings > |
HomeController
Right Click on Controller folder => Add => Controller.
Give a name to your controller.

Add a Index Action.
1
2
3
4
| public ActionResult Index() { return View(); } |
Now I have written methods in
HomeController
to Perform Crud Operations.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
| using System; using System.Linq; using System.Web.Mvc; using CrudInAj.Models; namespace CrudInAj.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); } public JsonResult GetAll() { using (DemoContext contextObj= new DemoContext()) { var employeeList = contextObj.employee.ToList(); return Json(employeeList,JsonRequestBehavior.AllowGet); } } public JsonResult GetEmployeeById( string id) { using (DemoContext contextObj= new DemoContext()) { int Id = Convert.ToInt32(id); var getEmployeeById = contextObj.employee.Find(Id); return Json(getEmployeeById,JsonRequestBehavior.AllowGet); } } public string UpdateEmployee(Employee emp) { if (emp != null ) { using (DemoContext contextObj = new DemoContext()) { int empId = Convert.ToInt32(emp.Id); Employee employee = contextObj.employee.Where(a => a.Id == empId).FirstOrDefault(); employee.Name = emp.Name; employee.Email = emp.Email; employee.Age = emp.Age; contextObj.SaveChanges(); return "Employee Updated" ; } } else { return "Invalid Record" ; } } public string AddEmployee(Employee employee) { if (employee != null ) { using (DemoContext contextObj = new DemoContext()) { contextObj.employee.Add(employee); contextObj.SaveChanges(); return "Employee Added" ; } } else { return "Invalid Record" ; } } public string DeleteEmployee( string employeeId) { if (!String.IsNullOrEmpty(employeeId)) { try { int Id = Int32.Parse(employeeId); using (DemoContext contextObj = new DemoContext()) { var getEmployee = contextObj.employee.Find(Id); contextObj.employee.Remove(getEmployee); contextObj.SaveChanges(); return "Employee Deleted" ; } } catch (Exception ex) { return "Employee Not Found" ; } } else { return "Invalid Request" ; } } } } |
1.
GetAll
Method.This method will return All the employee in Json formate.
2.
GetEmployeeById
Method.This method will return a single employee on the basis of EmployeeId.
Using EntityFramework query I have find the Employee using EmployeeId.
3.
UpdateEmployee
Method.This method takes Employee type parameter.
First we check Weather Employee Exist or not.
If yes then update the existing employee with new employee.
4.
AddEmployee
Method.This method also takes Employee type parameter.
First check whether the passed employee is null or not.
If not then Save the Employee.
5.
DeleteEmployee
Method.First we get the employee using given EmployeeId the remove that employee.
Now Let’s create Index view where we will show Employee List and the Perform Crud Operations .
Now Install Angularjs In Visual Studio.
Write the following code in
Index.cshtml
.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
| @{ ViewBag.Title = "Index"; } < div ng-controller = "myCntrl" > < span ng-click = "AddEmployeeDiv()" class = "btnGreen" > Add Employee </ span > < div class = "divList" > < p class = "divHead" >Employee List</ p > < table cellpadding = "12" > < tr > < td >< b >ID</ b ></ td > < td >< b >Name</ b ></ td > < td >< b >Email</ b ></ td > < td >< b >Age</ b ></ td > < td >< b >Actions</ b ></ td > </ tr > < tr ng-repeat = "employee in employees" > < td > {{employee.Id}} </ td > < td > {{employee.Name}} </ td > < td > {{employee.Email}} </ td > < td > {{employee.Age}} </ td > < td > < span ng-click = "editEmployee(employee)" class = "btnGreen" >Edit</ span > < span ng-click = "deleteEmployee(employee)" class = "btnRed" >Delete</ span > </ td > </ tr > </ table > </ div > < div ng-show = "divEmployee" > < p class = "divHead" >{{Action}} Employee</ p > < table > < tr > < td >< b >Id</ b ></ td > < td > < input type = "text" disabled = "disabled" ng-model = "employeeId" /> </ td > </ tr > < tr > < td >< b >Name</ b ></ td > < td > < input type = "text" ng-model = "employeeName" /> </ td > </ tr > < tr > < td >< b >Email</ b ></ td > < td > < input type = "text" ng-model = "employeeEmail" /> </ td > </ tr > < tr > < td >< b >Age</ b ></ td > < td > < input type = "text" ng-model = "employeeAge" /> </ td > </ tr > < tr > < td colspan = "2" > < input type = "button" class = "btnGreen" value = "Save" ng-click = "AddUpdateEmployee()" /> </ td > </ tr > </ table > </ div > </ div > |
one for showing List of employee, and one for performing Add and Update operations.
Above I have used Two AngularJs Directives .
ng-model
ng-click
Now create a folder inside Content folder.

Add Three Javascript Files.
1. Module.js : write the following code in it.
1
| var app = angular.module( "myApp" ,[]); |
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
| app.service( "angularService" , function ($http) { //get All Eployee this .getEmployees = function () { return $http.get( "Home/GetAll" ); }; // get Employee By Id this .getEmployee = function (employeeID) { var response = $http({ method: "post" , url: "Home/GetEmployeeById" , params: { id: JSON.stringify(employeeID) } }); return response; } // Update Employee this .updateEmp = function (employee) { var response = $http({ method: "post" , url: "Home/UpdateEmployee" , data: JSON.stringify(employee), dataType: "json" }); return response; } // Add Employee this .AddEmp = function (employee) { var response = $http({ method: "post" , url: "Home/AddEmployee" , data: JSON.stringify(employee), dataType: "json" }); return response; } //Delete Employee this .DeleteEmp = function (employeeId) { var response = $http({ method: "post" , url: "Home/DeleteEmployee" , params: { employeeId: JSON.stringify(employeeId) } }); return response; } }); |
In which I have create five functions for performing CRUD Operations .
These functions can be accessed from AngularJs Controller .
3. Controller.js : Write the following code .
AngularJs Controller Tutorial
To perform Create, Read, Update and delete ( CRUD Operations ) In angularJs I have Create three function in it.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
| app.controller( "myCntrl" , function ($scope, angularService) { $scope.divEmployee = false ; GetAllEmployee(); //To Get All Records function GetAllEmployee() { var getData = angularService.getEmployees(); getData.then( function (emp) { $scope.employees = emp.data; }, function () { alert( 'Error in getting records' ); }); } $scope.editEmployee = function (employee) { var getData = angularService.getEmployee(employee.Id); getData.then( function (emp) { $scope.employee = emp.data; $scope.employeeId = employee.Id; $scope.employeeName = employee.Name; $scope.employeeEmail = employee.Email; $scope.employeeAge = employee.Age; $scope.Action = "Update" ; $scope.divEmployee = true ; }, function () { alert( 'Error in getting records' ); }); } $scope.AddUpdateEmployee = function () { var Employee = { Name: $scope.employeeName, Email: $scope.employeeEmail, Age: $scope.employeeAge }; var getAction = $scope.Action; if (getAction == "Update" ) { Employee.Id = $scope.employeeId; var getData = angularService.updateEmp(Employee); getData.then( function (msg) { GetAllEmployee(); alert(msg.data); $scope.divEmployee = false ; }, function () { alert( 'Error in updating record' ); }); } else { var getData = angularService.AddEmp(Employee); getData.then( function (msg) { GetAllEmployee(); alert(msg.data); $scope.divEmployee = false ; }, function () { alert( 'Error in adding record' ); }); } } $scope.AddEmployeeDiv= function () { ClearFields(); $scope.Action = "Add" ; $scope.divEmployee = true ; } $scope.deleteEmployee = function (employee) { var getData = angularService.DeleteEmp(employee.Id); getData.then( function (msg) { GetAllEmployee(); alert( 'Employee Deleted' ); }, function (){ alert( 'Error in Deleting Record' ); }); } function ClearFields() { $scope.employeeId = "" ; $scope.employeeName = "" ; $scope.employeeEmail = "" ; $scope.employeeAge = "" ; } }); |
_Layout.cshtml
view => Shared => _Layout.cshtml
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
| <! DOCTYPE html> < html ng-app = "myApp" > < head > < meta charset = "utf-8" /> < meta name = "viewport" content = "width=device-width" /> < title >@ViewBag.Title</ title > < script src = "~/Scripts/angular.min.js" ></ script > < script src = "~/Content/Angular/Module.js" ></ script > < script src = "~/Content/Angular/Service.js" ></ script > < script src = "~/Content/Angular/Controller.js" ></ script > @Styles.Render("~/Content/css") < style > </ style > </ head > < body > @RenderBody() @Scripts.Render("~/bundles/jquery") @RenderSection("scripts", required: false) </ body > </ html > |
get the modified css in downloaded code.
DEMO

DOWNLOAD CODE
No comments:
Post a Comment