crud operations using web api with angularjs

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 Let’s 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.

Upload: tbijle

Post on 08-Nov-2015

15 views

Category:

Documents


3 download

DESCRIPTION

CRUD Operations Using Web API With AngularJS

TRANSCRIPT

CRUD Operations Using Web Api with AngularJSCRUD Operations Using Web Api with AngularJSIn Previous Tutorial, We have seenCRUD Operations in MVC with AngularJsNow 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 someHTTP 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 => ProjectSelect 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.

namespace StartWebApi.Models{ public class Employee { public int Id { get; set; } public string Name { get; set; } public string Email { get; set; } public int Age { get; set; } }}using System.Data.Entity;

namespace StartWebApi.Models{ public class DemoContext : DbContext { public DbSet employee { get; set; } }}Now Create a Api Controller. Name it asHomeApi

using StartWebApi.Models;using System.Collections.Generic;using System.Linq;using System.Web.Http;using System.Web.Http.Description;

namespace StartWebApi.Controllers{ public class HomeApiController : ApiController { public IEnumerable GetAll() { using (DemoContext objDemoContext = new DemoContext()) { return objDemoContext.employee.ToList(); } }

public IHttpActionResult Get(int Id) { using (DemoContext objDemoContext = new DemoContext()) { var employee = objDemoContext.employee.FirstOrDefault(a => a.Id == Id); if (employee != null) { return Ok(employee); } else { return NotFound(); } }

}

[ResponseType(typeof(Employee))] public IHttpActionResult Post(Employee employee) { using (DemoContext objDemoContext=new DemoContext()) { objDemoContext.employee.Add(employee); objDemoContext.SaveChanges(); } return CreatedAtRoute("DefaultApi", new { Id = employee.Id }, employee); }

[ResponseType(typeof(Employee))] public IHttpActionResult Delete(int Id) { using (DemoContext objDemoContext = new DemoContext()) { var GetEmployee = objDemoContext.employee.FirstOrDefault(a => a.Id == Id); if (GetEmployee != null) { objDemoContext.employee.Remove(GetEmployee); objDemoContext.SaveChanges(); return Ok(); } else { return NotFound(); } } }

[ResponseType(typeof(Employee))] public IHttpActionResult Put(int Id,Employee employee) { if (Id != employee.Id) { return BadRequest(); } else { using (DemoContext contextObj = new DemoContext()) {

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

}}

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

namespace StartWebApi.Controllers{ public class HomeController : Controller { public ActionResult Index() { return View(); } }}Now Install AngularJs in your Project.See the Previous ArticleHow to Install AngularJs in Visual Studio.Write down following code in Index.cshtml.

Add Employee

Employee List ID Name Email Age Actions {{employee.Id}} {{employee.Name}} {{employee.Email}} {{employee.Age}} Edit Delete

{{Action}} Employee Id Name Email Age

Create a folder inside content folder. name it as Angular.Add three Js file to it.Module.jsvar app = angular.module("myApp",[]);Service.jsWe will write code in service.Js file to Interact with Web Api to perform CRUD Operations.

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

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

// get Employee By Id this.getEmployee = function (employeeID) { return response = $http.get("/api/HomeApi/" + employeeID); }

// Update Employee this.updateEmp = function (employeeID, employee) { var response = $http({ method: "put", url: "/api/HomeApi/"+employeeID, data: JSON.stringify(employee), dataType: "json" }); return response; }

// Add Employee this.AddEmp = function (employee) { var response = $http({ method: "post", url: "/api/HomeApi", data: JSON.stringify(employee), dataType: "json" }); return response; }

//Delete Employee this.DeleteEmp = function (employeeId) { var response = $http({ method: "delete", url: "/api/HomeApi/" + employeeId }); return response; }});

$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(); //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 record'); }); }

$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($scope.employeeId,Employee); getData.then(function (msg) { GetAllEmployee(); alert("Employee Id :- " +msg.data.Id+ " is Updated"); $scope.divEmployee = false; }, function () { alert('Error in updating record'); }); } else { var getData = angularService.AddEmp(Employee); getData.then(function (msg) { GetAllEmployee(); alert("Employee Name :- "+msg.data.Name+" is Added"); $scope.divEmployee = false; }, function () { alert('Error in adding record'); }); } }

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

$scope