DotNetSlackers: ASP.NET News for lazy Developers

Friday, October 16, 2015

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.

CRUD Operations Using Web Api with AngularJS

Add the following two class to model folder.

01
02
03
04
05
06
07
08
09
10
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; }
    }
}
?
01
02
03
04
05
06
07
08
09
10
using System.Data.Entity;
namespace StartWebApi.Models
{
    public class DemoContext : DbContext
    {
        
        public DbSet<Employee> employee { get; set; }
    }
}

Now Create a Api Controller. Name it as HomeApi

CRUD Operations Using Web Api with AngularJS

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
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<Employee> 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.
?
01
02
03
04
05
06
07
08
09
10
11
12
using System.Web.Mvc;
namespace StartWebApi.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    }
}

Now Install AngularJs in your Project.

Write down 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
<div id="body">
    <div ng-controller="myCntrl" class="divList">
        <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>
</div>

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

Add three Js file to it.

Module.js

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

We will write code in service.Js file to Interact with Web Api 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
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 :

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 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.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 = "";
    }
});
Now we need to change the connectionstring in web.config file.

1
2
3
<connectionStrings>
    <add name="DemoContext" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-StartWebApi-20141228192300;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-StartWebApi-20141228192300.mdf" />
  </connectionStrings>
Open the _Layout.cshtml
Include AngularJs file inside head tag.

1
2
3
4
<script src="~/Scripts/angular.js"></script>
 <script src="~/Content/Angular/Module.js"></script>
 <script src="~/Content/Angular/Service.js"></script>
 <script src="~/Content/Angular/Controller.js"></script>

See the Previous Article, To know more about AngularJs Directives

We have done the CRUD Operations in MVC using Web Api and AngularJS.

DEMO
CRUD Operations in MVC with AngularJs
DOWNLOAD CODE

No comments:

Post a Comment