Tuesday, August 2, 2016

AngularJs: CRUD operations in Asp.net MVC 5

In this article I am going to explain how to perform Create, read, Update and Delete (CRUD) operations in Asp.net MVC 5 using AngularJs.

AngularJs CRUD operations in Asp.net MVC 5



Description:
In this angularjs tutorial I am going to perform create, read, update and delete (CRUD) operations.

Implementation:

I have created a table Employee. I want to insert, edit and delete employee information like name, phone number, email id etc. and also going to display all employees in grid.

Model (Employee.cs):
  public partial class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public Nullable<int> Phone { get; set; }
        public Nullable<int> Salary { get; set; }
        public string Department { get; set; }
        public string EmailId { get; set; }
    }


Add Controller
I have added empty controller to project. Now create a Json action for CRUD opration.

Compete code of Controller (Democontroller.cs):-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVC_Project.Models;
namespace MVC_Project.Controllers
{
    public class DemoController : Controller
    {
        //
        // GET: /Demo/
        DemoEntities1 db = new DemoEntities1();

        public ActionResult Index()
        {
            return View();
        }
        public JsonResult GetEmployee()
        {
            var emp = db.Employees.ToList();
            return Json(emp, JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        public JsonResult InsertEmployee(Employee emp)
        {
            db.Employees.Add(emp);
            db.SaveChanges();
            string message = "Success";
            return new JsonResult { Data = message, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

        [HttpPost]
        public JsonResult UpdateEmployee(int id, string name, string department, int phone, int salary, string emailId)
        {
            var emp = db.Employees.Where(x => x.Id == id).FirstOrDefault();
            emp.Name = name;
            emp.Phone = phone;
            emp.Department = department;
            emp.Salary = salary;
            emp.EmailId = emailId;          
            db.SaveChanges();
            return Json(emp, JsonRequestBehavior.AllowGet);
        }
        [HttpDelete]
        public JsonResult DeleteEmployee(int id)
        {
            Employee emp = db.Employees.Find(id);
            db.Employees.Remove(emp);
            db.SaveChanges();
            return Json(emp, JsonRequestBehavior.AllowGet);
        }
        [HttpGet]
        public JsonResult getByid(int id)
        {
            Employee emp = db.Employees.Find(id);
            return Json(emp, JsonRequestBehavior.AllowGet);
        }
      

    }
}



Add View
Add view for Index action.

Complete code of view (index.cshtml):

@{
    ViewBag.Title = "AngularJs Tutorial";
}
<style>

</style>
<h2>AngularJs Tutorial : CRUD operation</h2>
<div ng-app="mvcapp" ng-controller="DemoController">
    <form name="myform">
        <table class="table">
            <tr>
                <td>Name :</td>
                <td>
                    <input type="text" ng-model="empModel.Name" placeholder="Name" class='form-control' required />   
</td>
            </tr>
            <tr>
                <td>Phone :</td>
                <td>
                    <input type="text" ng-model="empModel.Phone" placeholder="Phone" class='form-control' required />
                </td>
            </tr>
            <tr>
                <td>Salary :</td>
                <td>
                    <input type="text" ng-model="empModel.Salary" placeholder="Salary" class='form-control' required />
                </td>
            </tr>
            <tr>
                <td>Department :</td>
                <td>
                    <input type="text" ng-model="empModel.Department" placeholder="Department" class='form-control' required />
                </td>
            </tr>
            <tr>
                <td>Email :</td>
                <td>
                    <input type="email" ng-model="empModel.EmailId" class='form-control' placeholder="Email" required />
                </td>
            </tr>
            <tr>
                <td></td>
                <td>
                    <input type="button" value="Save" id="btnsave" ng-disabled="isDisabledsave" ng-click="myform.$valid && saveCustomer()" />
                    <input type="button" value="Update" id="btnupdate" ng-disabled="isDisabledupdate" ng-click="myform.$valid && updateCustomer()" />
                </td>
            </tr>
        </table>
        </form>
        <table>
            <tr>
                <th>S.No</th>

                <th>
                    Name
                </th>
                <th>
                    Phone
                </th>
                <th>
                    Department
                </th>
                <th>
                    Salary
                </th>
                <th>
                    Email
                </th>
            </tr>
            <tr ng-repeat="empModel in employees">
                <td>{{empModel.Id}}</td>
                <td>{{empModel.Name }}</td>
                <td>{{empModel.Phone }}</td>
                <td>{{empModel.Department}}</td>
                <td>{{empModel.Salary }}</td>
                <td>{{empModel.EmailId ||'Email not available'}}</td>
                <td>
                    <a href="" ng-click="getCustomer(empModel)" title="Delete Record">Edit</a>  |
                    <a href="" ng-click="deleteemp(empModel)" title="Delete Record">
                        Delete
                    </a>
                </td>
            </tr>
        </table>

</div>

<style>
    input[type=button][disabled=disabled] {
        opacity: 0.65;
        cursor: not-allowed;
    }
    table tr th {
        padding: 10px 30px;
    }
    table tr td {
        padding: 10px 30px;
    }
</style>

<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">  
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.js"></script>
<script>
    var angular = angular.module('mvcapp', []);

    angular.controller('DemoController', function ($scope, $http) {
      
        GetAllData();
        $scope.isDisabledupdate = true;
        //Get All Employee
        function GetAllData() {
            $http.get('/Demo/GetEmployee').success(function (data) {
                $scope.employees = data;
            });
        };

        //Insert Employee
        $scope.saveCustomer = function () {
            debugger
            $http({
                method: 'POST',
                url: '/Demo/InsertEmployee',
                data: $scope.empModel
            }).success(function () {                              
                    GetAllData();                   
                    $scope.empModel =null;                  
                    alert("Employee Added Successfully!!!");
            }).error(function () {
                alert(data.errors);
            });
            GetAllData();
        };

        //Delete Employee
        $scope.deleteemp = function (empModel) {
            debugger
            varIsConf = confirm('Want to delete ' + empModel.Name + '. Are you sure?');
            if (varIsConf) {
                $http.delete('/Demo/DeleteEmployee/' + empModel.Id).success(function () {
                    $scope.errors = [];                  
                    GetAllData();
                    alert(empModel.Name + " Deleted Successfully!!!");
                }).error(function () {
                    alert(data.errors);
                });
            }
        };

        //Get Employee by id to edit
        $scope.getCustomer = function (empModel) {
            $http.get('/Demo/getByid/' + empModel.Id)
            .success(function (data, status, headers, config) {
                //debugger;
                $scope.empModel = data;
                GetAllData();
                $scope.isDisabledsave = true;
                $scope.isDisabledupdate = false;
            })
            .error(function () {
                alert(data.errors);
            });
        };

        //Update Employee
        $scope.updateCustomer = function () {
            debugger
            $http({
                method: 'POST',
                url: '/Demo/UpdateEmployee',
                data: $scope.empModel
            }).success(function () {
                GetAllData();
                $scope.isDisabledsave = false;
                $scope.isDisabledupdate = true;
                $scope.empModel = null;
                alert("Employee Updated Successfully!!!");
            }).error(function () {
                alert(data.errors);
            });
        };
      
    });
</script>


You have done it successfully. Now build and run the project. To test it makes some entries. Cheers!!!
  

2 comments:

  1. Hello sir
    I have tried this article
    but data did not inserted and Angularjs not working
    Reply me sooon

    ReplyDelete
    Replies
    1. What is the error u are getting? Check in console

      Delete