CRUD Operations in MVC With AngularJs

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 11

CRUD Operations in MVC with AngularJs.

In this Tutorial, Ill show you How to perform CRUD Operations in MVC with
AngularJs.
AngularJs Is Javascript framework to SPA (Single Page Application).
AngularJS extends HTML by providing Directives that add functionality to your
markup and allow you to create powerful dynamic templates.
There are any Advantage of using AngularJs.
In this Tutorial I have Used Employee table to Perform Create, Read, Update and
Delete (CRUD Operations).
Lets 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; }
}
}

Add one more model class.


?

1
using System.Data.Entity;
2
namespace CrudInAj.Models
3
{
public class DemoContext:DbContext
4
{
5
public DbSet<Employee> employee { get; set; }
6
}
7
}
8
Now modify your connectionstring according to your context class.
?

1
2
3

<connectionStrings>
<add name="DemoContext" providerName="System.Data.SqlClient" connectionString="Da
Source=(LocalDb)\v11.0;Initial Catalog=aspnet-CrudInAj-20141222205150;Integrated
Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-CrudInAj-20141222205150.mdf" /
</connectionStrings>

Create a HomeController
Right Click on Controller folder => Add => Controller.
Give a name to your controller.

Add a Index Action.


?

1
public ActionResult Index()
{
2
return View();
3
}
4
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

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";
}
}

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

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";
}
}
}
}

95
96
97
98
99
Now Lets understand the above method one by one.
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 Lets 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

@{

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>

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

<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 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" ngclick="AddUpdateEmployee()" />
</td>
</tr>

64
65
66
67
68
69
70
71
72
73
74
75
76
77

</table>
</div>
</div>

I have created Two table .


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.
?

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


1
2. Service.js : Write the following code in it.
?

01

app.service("angularService", function ($http) {

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

//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;
}
});

52
53
Above I have created an AngularJs Services (Name : angularService)
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

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;

38
39
40
41
42
43
44
}, function () {
45
alert('Error in updating record');
46
});
47
} else {
var getData = angularService.AddEmp(Employee);
48
getData.then(function (msg) {
49
GetAllEmployee();
50
alert(msg.data);
51
$scope.divEmployee = false;
}, function () {
52
alert('Error in adding record');
53
});
54
}
55
}
56
57
$scope.AddEmployeeDiv=function()
{
58
ClearFields();
59
$scope.Action = "Add";
60
$scope.divEmployee = true;
61
}
62
63
$scope.deleteEmployee = function (employee)
{
64
var getData = angularService.DeleteEmp(employee.Id);
65
getData.then(function (msg) {
66
GetAllEmployee();
67
alert('Employee Deleted');
},function(){
68
alert('Error in Deleting Record');
69
});
70
}
71
72
function ClearFields() {
73
$scope.employeeId = "";
$scope.employeeName = "";
74
$scope.employeeEmail = "";
75
$scope.employeeAge = "";
76
}
77
});
78
79
80
81
82
83
84
Inculde These Js file in your _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>

We have done the CRUD Operations in MVC with angularJS.


get the modified css in downloaded code.

You might also like