CRUD Operations using AngularJS and WebAPI with MVC

Steps to build MVC CRUD operations using AngularJS and WebAPI

Step1: 

Create a MVC web application in visual studio

Step-2: 

Create a MDF file inside APP_Data folder.

Step-3: 

 Now create a table and single stored procedure to perform CRUD operations.

 

CREATE TABLE [dbo].[Employee]
(
       [Id] INT NOT NULL IDENTITY (1,1),
       [Name] nvarchar(50) Not null,
       [Address] nvarchar(50) not null,
       [Country] nvarchar(50) not null,
       [City] nvarchar(50) not null,
       [Mobile] nvarchar(10) not null,
       PRIMARY KEY CLUSTERED([Id] ASC)
);

Stored Procedure for CRUD Operation

CREATE PROCEDURE USP_InsUpdDelEmployee
@id int,
@name nvarchar(50),
@address nvarchar(50),
@Country nvarchar(50),
@city nvarchar(50),
@mobile nvarchar(50),
@type varchar(10)
 
As
Begin
if (@type='Ins') Begin
Insert into Employee
Values (@name,@address,@Country,@city,@mobile)
  End
  if(@type='Upd') Begin
  Update Employee Set Name=@name, Address=@address, Country=@Country, 
City=@city,Mobile=@mobile where Id=@id
  End
  if(@type='Del') Begin
  Delete from Employee where Id=@id
  end
  if(@type='GetById') Begin
 
  Select * from Employee where Id=@id
  End
  Select * From Employee
  End

 

Step-4:

Right click on models and create entity-data model then automatically connection will be created in web.config file.

Step-5:

Right click on controllers folder,create webapi empty controller and paste below code

public class EmployeeAPIController : ApiController
{

[HttpGet]
public List Get()
{
List emplist = new List();
using (MydatabaseEntities dc = new MydatabaseEntities())
{
var results = dc.USP_InsUpdDelEmployee(0, "", "", "", "", "", "Get").ToList();
foreach(var result in results)
{
var employee = new Employee()
{
Id = result.Id,
Name = result.Name,
Address = result.Address,
Country = result.Country,
City = result.City,
Mobile = result.Mobile
};
emplist.Add(employee);
}
return emplist;
}
}

public Employee Get(int id)
{
using (MydatabaseEntities dc = new MydatabaseEntities())
{
Employee employee = dc.Employees.Find(id);
if (employee == null)
{
throw newHttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
}
return employee;
}
}

public HttpResponseMessage Post(Employee employee)
{
if (ModelState.IsValid)
{
using (MydatabaseEntities dc = new MydatabaseEntities())
{
var emplist = dc.USP_InsUpdDelEmployee
(0, employee.Name, employee.Address, employee.Country, employee.City, employee.Mobile,"Ins").ToList();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, emplist);
return response;
}
} else
{
return Request.CreateResponse(HttpStatusCode.BadRequest, ModelState);
}
}

public HttpResponseMessage Put(Employee employee)
{
List emplist = newList();
if (!ModelState.IsValid)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
using(MydatabaseEntities dc=new MydatabaseEntities())
{
try
{
emplist = dc.USP_InsUpdDelEmployee
(employee.Id, employee.Name, employee.Address, employee.Country, employee.City, employee.Mobile, "Upd").ToList();

}
catch (DbUpdateConcurrencyException ex)
{

returnRequest.CreateErrorResponse(HttpStatusCode.NotFound,ex);
}
return Request.CreateResponse(HttpStatusCode.OK, emplist);
}
}

public HttpResponseMessage Delete(int id)
{
using(MydatabaseEntities dc=new MydatabaseEntities())
{
List emplist = newList();
var results = dc.USP_InsUpdDelEmployee(id, "", "", "", "", "", "GetById").ToList();
if (results.Count==0)
{
return Request.CreateResponse(HttpStatusCode.NotFound);
}
try
{
emplist = dc.USP_InsUpdDelEmployee(id, "", "", "", "", "", "Del").ToList();
}
catch (DbUpdateConcurrencyException ex)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
throw;
}
return Request.CreateResponse(HttpStatusCode.OK, emplist);
}
}

protected override void Dispose(bool disposing)
{
using (MydatabaseEntities dc = new MydatabaseEntities())
dc.Dispose();
base.Dispose(disposing);
}
}
}

Step-6:

Create another controller for MVC to create view.

 


public class TestController : Controller
    {
        // GET: Test
        public ActionResult Index()
        {
            return View();
        }
    }

Step-7:

Load angular js files from this url: https://www.angularjs.org/ (or) use CDN files.

Step-8:

Create javascript file to write angular code like below.


var app = angular.module('myapp', []);
app.controller('employeeController', ['$scope', '$http', employeeController]);
 
function employeeController($scope,$http)
{
    $scope.loading = true;
    $scope.updateShow = false;
    $scope.addShow = true;
    $http.get('/api/EmployeeAPI', this.newemployee).success(function (data) {
        $scope.employees = data;
    }).error(function () {
        $scope.error = 'An error has occured while posting';
    });
 
    $scope.add = function () {
        $scope.loading = true;
        $http.post('/api/EmployeeAPI', this.newemployee).success(function (data) {
            $scope.employees = data;
            $scope.updateShow = false;
            $scope.addShow = true;
            $scope.newemployee = '';
        }).error(function (data) {
            $scope.error = "error while saving" + data;
        });
    }
 
    $scope.edit = function () {
        var Id = this.employee.Id;
        $http.get('/api/EmployeeAPI/' + Id).success(function (data) {
            $scope.newemployee = data;
            $scope.updateShow = true;
            $scope.addShow = false;
        }).error(function () {
            $scope.error = "An Error has occured while loading posts!";
        });
    }
    $scope.update = function () {
        $scope.loading = true;
        console.log(this.newemployee);
        $http.put('/api/EmployeeAPI/', this.newemployee).success(function (data) {
            $scope.employees = data;
            $scope.updateShow = false;
            $scope.addShow = true;
            $scope.newemployee = '';
        }).error(function (data) {
            $scope.error = "An Error has occured while Updating employee! " + data;
        });
    }
    $scope.delete = function () {
        var Id = this.employee.Id;
        $scope.loading = true;
        $http.delete('/api/EmployeeAPI/' + Id).success(function (data) {
            $scope.employees = data;
        }).error(function (data) {
            $scope.error = "An Error has occured while Delete employee! " + data;
        });
    }
    $scope.cancel = function () {
        $scope.updateShow = false;
        $scope.addShow = true;
        $scope.newemployee = '';
    }
}

Step-9:

Create an index view and paste below code

 

@{

    Layout = “~/Views/Shared/_Layout.cshtml”;

}

<html ng-app=”myapp”>

<head>

    <title>MVC AngularJs With WebApi</title>

</head>

<body>

    <div ng-controller=”employeeController class=”container”>

        <div class=”row”>

            <div class=”col-md-12″>

                <h3 class=”header”>EMPLOYEE CRUD USING ANGULARJS AND WEBAPI</h3>

            </div>

        </div>

        <div class=”row”>

            <div class=”col-md-12″>

                <strong class=”error”>{{error}}</strong>

                <form name=”addemployee” style=”width600pxmargin0px auto;“>

                    <div class=”form-group”>

                        <label for=”cname” class=”col-sm-2 control-label”>Name:</label>

                        <div class=”col-sm-10 space”>

                            <input type=”text” class=”form-control” id=”cname”placeholder=”please enter your name” ng-model=”newemployee.Name required />

                        </div>

                    </div>

                    <div class=”form-group”>

                        <label for=”address” class=”col-sm-2 control-label”>Address:</label>

                        <div class=”col-sm-10 space”>

                            <textarea class=”form-control” id=”address”placeholder=”please enter your address” ng-model=”newemployee.Address required></textarea>

                        </div>

                    </div>

                    <div class=”form-group”>

                        <label for=”country” class=”col-sm-2 control-label”>Domicile:</label>

                        <div class=”col-sm-10 space”>

                            <input type=”text” class=”form-control” id=”country”placeholder=”please enter your native” ng-model=”newemployee.Country required />

                        </div>

                    </div>

                    <div class=”form-group”>

                        <label for=”city” class=”col-sm-2 control-label”>Town:</label>

                        <div class=”col-sm-10 space”>

                            <input type=”text” class=”form-control” id=”city”placeholder=”please enter your town” ng-model=”newemployee.City required />

                        </div>

                    </div>

                    <div class=”form-group”>

                        <label for=”mobile” class=”col-sm-2 control-label”>Contact:</label>

                        <div class=”col-sm-10 space”>

                            <input type=”text” class=”form-control” id=”mobile”placeholder=”please enter your Contact no.” ng-model=”newemployee.Mobilerequired />

                        </div>

                    </div>

                    <br />

                    <div class=”form-group space”>

                        <div class=”col-sm-offset-2 col-sm-10″>

                            <input type=”submit” value=”Insert” ng-click=”add()ng-show=”addShow ng-disabled=”!addemployee.$valid class=”btn btn-primary” />

                            <input type=”submit” value=”Update” ng-click=”update() ng-show=”updateShow ng-disabled=”!addemployee.$validclass=”btn btn-primary” />

                            <input type=”button” value=”Reset” ng-click=”cancel() class=”btn btn-primary” />

                        </div>

                    </div>

                    <br />

                </form>

            </div>

        </div>

        <div class=”row”>

            <div class=”col-md-12″>

                <div class=”table-responsive”>

                    <table class=”table table-bordered table-hover” style=”width800pxmargin-left170px;“>

                        <tr>

                            <th>Name</th>

                            <th>Address</th>

                            <th>Domicile</th>

                            <th>Town</th>

                            <th>Contact</th>

                            <th>Actions</th>

                        </tr>

                        <tr ng-repeat=”employee in employees“>

                            <td>

                                <p>{{ employee.Name }}</p>

                            </td>

                            <td>

                                <p>{{ employee.Address }}</p>

                            </td>

                            <td>

                                <p>{{ employee.Country }}</p>

                            </td>

                            <td>

                                <p>{{ employee.City }}</p>

                            </td>

                            <td>

                                <p>{{ employee.Mobile }}</p>

                            </td>

                            <td>

                                <p><a ng-click=”edit()href=”javascript:void(0);”>Edit</a> | <a ng-click=”delete()href=”javascript:void(0);”>Delete</a></p>

                            </td>

                        </tr>

                    </table>

                </div>

            </div>

        </div>

    </div>

    

</body>

</html>  

 

Step-10:

Finally run the project and you get the output as you expected.

Good Luck:)

One Reply to “CRUD Operations using AngularJS and WebAPI with MVC”

Leave a Reply

Your email address will not be published. Required fields are marked *