Você está na página 1de 17

CRUD Operations Using Web Api with AngularJS

CRUD Operations Using Web Api with AngularJS


In Previous Tutorial, We have seen CRUD Operations in MVC with AngularJs
Now We will perform Same Create, Read, Update and Delete ( CRUD Operations )
using Web Api with AngularJS.

Web Api is light weight Technology to build RESTfull


Web Services.
Web Api is framework to build HTTP services that can
be consumed by various clients.
To perform CRUD Operations, We will use some HTTP verbs, which is listed
below.

GET : It is used for Get data.


POST : It is used to create a new resource.
PUT : It is used to update the existing resource.
DELETE : It is used to Delete the resources.

Now Lets Create MVC application.


File => New => Project
Select Asp.Net MVC4 Application, Click OK.
A pop up window will open, Select Web Api from there.

Add the following two class to model folder.

namespaceStartWebApi.Models
{
publicclassEmployee
{
publicintId{get;set;}
publicstringName{get;set;}
publicstringEmail{get;set;}
publicintAge{get;set;}
}
}
usingSystem.Data.Entity;

namespaceStartWebApi.Models
{
publicclassDemoContext:DbContext
{

publicDbSet<Employee>employee{get;set;}
}
}

Now Create a Api Controller. Name it as HomeApi

usingStartWebApi.Models;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Web.Http;
usingSystem.Web.Http.Description;

namespaceStartWebApi.Controllers
{
publicclassHomeApiController:ApiController
{
publicIEnumerable<Employee>GetAll()
{
using(DemoContextobjDemoContext=newDemoContext())
{
returnobjDemoContext.employee.ToList();
}
}

publicIHttpActionResultGet(intId)
{
using(DemoContextobjDemoContext=newDemoContext())
{
varemployee=objDemoContext.employee.FirstOrDefault(a
=>a.Id==Id);
if(employee!=null)
{
returnOk(employee);
}
else
{
returnNotFound();
}
}

[ResponseType(typeof(Employee))]
publicIHttpActionResultPost(Employeeemployee)
{
using(DemoContextobjDemoContext=newDemoContext())
{

objDemoContext.employee.Add(employee);
objDemoContext.SaveChanges();
}
returnCreatedAtRoute("DefaultApi",new{Id=
employee.Id},employee);
}

[ResponseType(typeof(Employee))]
publicIHttpActionResultDelete(intId)
{
using(DemoContextobjDemoContext=newDemoContext())
{
varGetEmployee=
objDemoContext.employee.FirstOrDefault(a=>a.Id==Id);
if(GetEmployee!=null)
{
objDemoContext.employee.Remove(GetEmployee);
objDemoContext.SaveChanges();
returnOk();
}
else
{
returnNotFound();
}

}
}

[ResponseType(typeof(Employee))]
publicIHttpActionResultPut(intId,Employeeemployee)
{
if(Id!=employee.Id)
{
returnBadRequest();
}
else
{
using(DemoContextcontextObj=newDemoContext())
{

EmployeeGetEmployee=
contextObj.employee.Find(Id);
GetEmployee.Name=employee.Name;
GetEmployee.Email=employee.Email;
GetEmployee.Age=employee.Age;
contextObj.SaveChanges();
returnCreatedAtRoute("DefaultApi",new{Id=
employee.Id},employee);
}

}
}

}
}

Above Five method is created to perform crud operration using Web Api.
Now create a Home Controller.
usingSystem.Web.Mvc;

namespaceStartWebApi.Controllers
{
publicclassHomeController:Controller
{
publicActionResultIndex()
{
returnView();
}
}
}

Now Install AngularJs in your Project.


See the Previous Article How to Install AngularJs in Visual Studio .

Write down following code in Index.cshtml.

<divid="body">
<divngcontroller="myCntrl"class="divList">

<spanngclick="AddEmployeeDiv()"class="btnGreen">
AddEmployee
</span>

<divclass="divList">
<pclass="divHead">EmployeeList</p>
<tablecellpadding="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>
<trngrepeat="employeeinemployees">
<td>
{{employee.Id}}
</td>

<td>
{{employee.Name}}
</td>
<td>
{{employee.Email}}
</td>
<td>
{{employee.Age}}
</td>
<td>
<spanngclick="editEmployee(employee)"
class="btnGreen">Edit</span>
<spanngclick="deleteEmployee(employee)"
class="btnRed">Delete</span>
</td>
</tr>
</table>
</div>

<divngshow="divEmployee">
<pclass="divHead">{{Action}}Employee</p>
<table>
<tr>
<td><b>Id</b></td>

<td>
<inputtype="text"disabled="disabled"ng
model="employeeId"/>
</td>
</tr>
<tr>
<td><b>Name</b></td>
<td>
<inputtype="text"ngmodel="employeeName"/>
</td>
</tr>
<tr>
<td><b>Email</b></td>
<td>
<inputtype="text"ngmodel="employeeEmail"/>
</td>
</tr>
<tr>
<td><b>Age</b></td>
<td>
<inputtype="text"ngmodel="employeeAge"/>
</td>
</tr>

<tr>
<tdcolspan="2">
<inputtype="button"class="btnGreen"
value="Save"ngclick="AddUpdateEmployee()"/>
</td>
</tr>
</table>
</div>
</div>
</div>

Create a folder inside content folder. name it as Angular.


Add three Js file to it.
Module.js
varapp=angular.module("myApp",[]);

Service.js
We will write code in service.Js file to Interact with Web Api to perform CRUD
Operations.

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

//getAllEployee

this.getEmployees=function(){
return$http.get("/api/HomeApi");
};

//getEmployeeById
this.getEmployee=function(employeeID){
returnresponse=$http.get("/api/HomeApi/"+employeeID);

//UpdateEmployee
this.updateEmp=function(employeeID,employee){
varresponse=$http({
method:"put",
url:"/api/HomeApi/"+employeeID,
data:JSON.stringify(employee),
dataType:"json"
});
returnresponse;
}

//AddEmployee
this.AddEmp=function(employee){
varresponse=$http({
method:"post",
url:"/api/HomeApi",
data:JSON.stringify(employee),
dataType:"json"
});
returnresponse;
}

//DeleteEmployee
this.DeleteEmp=function(employeeId){
varresponse=$http({
method:"delete",
url:"/api/HomeApi/"+employeeId
});
returnresponse;
}
});

$http.get (url) : It will send HTTP get request.


$http.post (url, data) : It will send HTTP post request.
$http.put (url,data) : It will send HTTP put request.
$http.delete (url) : It will send HTTP delete request.

Controller.js :
app.controller("myCntrl",function($scope,angularService){
$scope.divEmployee=false;
GetAllEmployee();
//ToGetAllRecords
functionGetAllEmployee(){
vargetData=angularService.getEmployees();
getData.then(function(emp){
$scope.employees=emp.data;
},function(){
alert('Erroringettingrecords');
});
}

$scope.editEmployee=function(employee){
vargetData=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('Erroringettingrecord');
});
}

$scope.AddUpdateEmployee=function()
{
varEmployee={
Name:$scope.employeeName,
Email:$scope.employeeEmail,
Age:$scope.employeeAge
};
vargetAction=$scope.Action;

if(getAction=="Update"){
Employee.Id=$scope.employeeId;
vargetData=
angularService.updateEmp($scope.employeeId,Employee);

getData.then(function(msg){
GetAllEmployee();
alert("EmployeeId:"+msg.data.Id+"isUpdated");
$scope.divEmployee=false;
},function(){
alert('Errorinupdatingrecord');
});
}else{
vargetData=angularService.AddEmp(Employee);
getData.then(function(msg){
GetAllEmployee();
alert("EmployeeName:"+msg.data.Name+"isAdded");
$scope.divEmployee=false;
},function(){
alert('Errorinaddingrecord');
});
}
}

$scope.AddEmployeeDiv=function()
{
ClearFields();
$scope.Action="Add";

$scope.divEmployee=true;
}

$scope