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:)

TempData in MVC

TempData used to store temporary data which can be used in the subsequent request by the user. TempData will be cleared out after the completion of a subsequent request.

TempData is useful when you want to transfer non-sensitive data from one action method to another action method of the same or a different controller as well as redirects. It is dictionary type which is derived from TempDictionary.

Adding a key-value pair in TempData as shown in the below example.

Example: TempData

public class AventController : Controller
{
    // GET: Student
    public AventController()
    {

    }
    public ActionResult Index()
    {
        TempData["name"] = "Test data";
        TempData["age"] = 30;

        return View();
    }

    public ActionResult About()
    {
        string userName;
        int userAge;
        
        if(TempData.ContainsKey("name"))
            userName = TempData["name"].ToString();
    
        if(TempData.ContainsKey("age"))
            userAge = int.Parse(TempData["age"].ToString());
    
        // do something with userName or userAge here 

        return View();
    }
}

In the above code, we added data into TempData and accessed the same data using a key inside another action method. Notice that we have converted values into the appropriate type.

 

As you can see in the above example, we add test data in TempData in the first request and in the second subsequent request we access test data from TempData which we stored in the first request. However, you can’t get the same data in the third request because TempData will be cleared out after second request.

Call TempData.Keep() to retain TempData values in a third consecutive request.

Example: TempData.Keep()

public class AventController : Controller
{
    // GET: Student
    public AventController()
    {

    }
    public ActionResult Index()
    {
        TempData["myData"] = "Test data";
        return View();
    }

    public ActionResult About()
    {
        string data;
        
        if(TempData["myData"] != null)
            data = TempData["myData"] as string;
        
        TempData.Keep();
        
        return View();
    }

    public ActionResult Contact()
    {
        string data;
        
        if(TempData["myData"] != null)
            data = TempData["myData"] as string;
            
        return View();
    }

}

New Features in .Net framework 4.5 and 5.0

Explaining the following features:

  • Parallel foreach
  • BigInteger
  • Expando Objects
  • Named and Optional Parameters
  • Tuple

1. Parallel.ForEach

Parallel.ForEach is a feature introduced by the Task Parallel Library (TPL). This feature helps you run your loop in parallel. You need to have a multi-processor to use of this feature.

Simple foreach loop

foreach (string i in listStrings)

{

……….

}

Parallel foreach

Parallel.Foreach(listStrings, text=>
{
……………………..
});

2. BigInteger

BigInteger is added as a new feature in the System.Numerics DLL. It is an immutable type that represents a very large integer whose value has no upper or lower bounds.

BigInteger obj = new BigInteger(“123456789123456789123456789”);

3. ExpandoObject

The ExpandoObject is part of the Dynamic Language Runtime (DLR). One can add and remove members from this object at run time.

Create a dynamic instance.

dynamic Person = new ExpandoObject();

Person.ID = 1001;

Person.Name = “Princy”;

Person.LastName = “Gupta”;

4. Named and Optional Parameters

Optional Parameters

A developer can now have some optional parameters by providing default values for them. PFB how to create optional parameters.

Void PrintName(string a, string b, string c = “princy”)

{

Console.Writeline(a, b, c)

}

We can now call the function PrinctName() by passing either two or three parameters as in the following:

PrintName(“Princy”,”Gupta”,”Jain”);
PrinctName(“Princy”,”Gupta”);

Output

PrincyGuptaJain
PrincyGuptaprincy

Note: An optional parameter can only be at the end of the parameter list.

Named Parameters

With this new feature the developer can pass values to parameters by referring to parameters by names.

Void PrintName(string A, string B

{

}

Function call

PrintName (B: “Gupta”, A: “Princy”);

With this feature we don’t need to pass parameters in the same order to a function.

5. Tuple

A Tuple provides us the ability to store various types in a single object.

The following shows how to create a tuple.

Tuple<int, string, bool> tuple = new Tuple<int, string, bool>(1,”princy”, true);

Var tupleobj = Tuple.Create(1, “Princy”, true);

In order to access the data inside the tuple, use the following:

string name = tupleobj.Item2;

int age = tupleobj.Item1;

bool obj = tupleobj.Item3;