Monday 13 June 2016

CRUD operations using AngularJS in Asp.Net MVC

In this article I will show you how to perform CRUD operations in Asp.Net MVC5 using AngularJS.

Add AngularJS using the Manage Nuget Package Manager.
Add Entity Data Model.

AngularJS Script with App initialization, Service/Factory and Controller code
Use the below code

var PersonApp = angular.module('PersonApp', []);

PersonApp.factory('PersonService', ['$http', function ($http) {

    return {
        getPersons: function () {
            return $http.get('/Person/GetPesrons');
        },
        addPerson: function (person) {
            return $http.post('/Person/AddPerson', person);
        },
        deletePerson: function (Id) {
            return $http.post('/Person/DeletePerson?id=' + Id);
        },
        updatePerson: function (person) {
            return $http.post('/Person/UpdatePerson' + person.Id, person);
        }
    }
}]);

PersonApp.controller('PersonController', function ($scope, PersonService) {

    //get all Customers
    PersonService.getPersons().success(function (data) {
        $scope.persons = data;
    })
    .error(function (data) {
        alert("An Error has occured while loading data! " + data.ExceptionMessage);
    });

    // add Person
    $scope.personSubmit = function () {
        var people = {};
        people["Name"] = $scope.Name;
        people["City"] = $scope.City;
        people["Contact"] = $scope.Contact;
        PersonService.addPerson(people).success(function (data) {
            alert("Added Successfully!!");
            window.location.href = '/Person/Index';
        }).error(function (data) {
            alert("An Error has occured while Adding person! " + data.ExceptionMessage);
        });
    };

    // delete Person
    $scope.delperson = function () {
        var currentPerson = this.prsn;
        PersonService.deletePerson(currentPerson.Id).success(function (data) {
            alert(data);
            window.location.href = '/Person/Index';
        }).error(function (data) {
            alert("An Error has occured while deleting person! " + data.ExceptionMessage);
        });
    }
});

MVC Controller code:
Try to add the below code in the controller to perform insert, retrieve and delete records.

public class PersonController : Controller
    {
        private PersonEntities dbe = new PersonEntities();
        // GET: Person
        public ActionResult Index()
        {
            return View();
        }
        public JsonResult GetPesrons()
        {
           

            var result = from a in dbe.People
                         select new
                         {
                             a.Id,
                             a.Name,
                             a.City,
                             a.Contact,
                             date = a.CreatedDate.ToString()
                         };
            return Json(result, JsonRequestBehavior.AllowGet);
        }
        public ActionResult Create()
        {
            return View();
        }
        public JsonResult AddPerson(Person model)
        {
            model.CreatedDate = DateTime.Now;
            dbe.People.Add(model);
            dbe.SaveChanges();
            return Json(model, JsonRequestBehavior.AllowGet);
        }
        public JsonResult DeletePerson(int id)
        {
            var result = "";
            Person p = dbe.People.Find(id);
            if (p != null)
            {
                dbe.People.Remove(p);
                dbe.SaveChanges();
                result = "Deleted Successfully!!";
            }
            else
            {
                result = "An Error has occured please try again!";
            }
            return Json(result, JsonRequestBehavior.AllowGet);
        }
    }



Create View code:
 Add below code in the create view.

<h2>Create Person</h2>
<script src="~/scripts/App/PersonClinet.js"></script>

<div ng-app="PersonApp" class="container">
    <div ng-controller="PersonController" class="form-group">
        <table class="table-condensed">
            <tr>
                <td><label class="control-label">Name</label></td>
                <td><input class="form-control" type="text" ng-model="Name" /></td>
            </tr>
            <tr>
                <td><label class="control-label">City</label></td>
                <td><input class="form-control" type="text" ng-model="City" /></td>
            </tr>
            <tr>
                <td><label class="control-label">Contact</label></td>
                <td><input class="form-control" type="text" ng-model="Contact" /></td>
            </tr>
            <tr>
                <td><input class="btn btn-danger" type="button" value="Back" /></td>
                <td><input class="btn btn-success btn-group-lg" type="button" ng-click="personSubmit()" value="Save" /></td>
            </tr>
        </table>
    </div>
</div>
Index View code:

Add below code in the Index view.


<script src="~/scripts/App/PersonClinet.js"></script>
<div ng-app="PersonApp" class="container">
    <div ng-controller="PersonController">
        <table class="table table-bordered table-striped table-hover table-responsive">
            <tr class="danger">
                <th>Name</th>
                <th>City</th>
                <th>Contact</th>
                <th>Created Date</th>
                <th>Actions</th>
            </tr>
            <tr ng-repeat="prsn in persons ">
                <td>{{prsn.Name}}</td>
                <td>{{prsn.City}}</td>
                <td>{{prsn.Contact}}</td>
                <td>{{prsn.date}}</td>
                <td>
                    <p><a href="javascript:;"><span class="glyphicon glyphicon-edit" aria-hidden="true"></span></a> |
                    <a data-ng-click="delperson(prsn)" href="javascript:;"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span></a></p>                  
                </td>
            </tr>
        </table>
    </div>
</div>