Codechef4u is a community for computer professionals,by computer professionals,just like you; who loves sharing and helping each others,Join them
Share your post

CRUD Operation in ASP.NET MVC and AngularJS

Insert,Update,Delete in AngularJS and ASP.NET MVC 

In this post I will create sample Asp.net MVC 4 application using AngularJS and perform

CRUD (Create, Read, Update and Delete) operations using SPA (Single Page Application).

First create Asp.net MVC 4 application named “AngularMVC” and then simply follow below steps.

1.  Now create a new Employee class in model folder with name as Employee.cs and add below listed properties.

   public class Employee
     {
 
        [Key]
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public string Address { get; set; }
     }


2. Now create entity EmployeeContext.cs class in model folder.

  namespace AngularMVC.Models
  {
    public class EmployeeContext : DbContext
    {
        public EmployeeContext() : base("DefaultConnection")
        {
        }
 
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            Database.SetInitializer<EmployeeContext>(null);
        }
        public DbSet<Employee> EmployeeData { get; set; }
    }
  }


3. Now let's add following code in HomeController to Retrieve, Insert, Update and delete Employee records.

       // GET: All Employees
        public JsonResult GetAllEmployees()
        {
            using (EmployeeContext contextObj = new EmployeeContext()))
            {
                var EmployeeList = contextObj.EmployeeData.ToList();
                return Json(EmployeeList, JsonRequestBehavior.AllowGet);
            }
        }
 
        // Insert/ADD new employee
        public JsonResult Save(Employee data)
        {
            using (EmployeeContext contextObj = new EmployeeContext())
            {
                var EmployeeList = contextObj.EmployeeData.Add(data);
                contextObj.SaveChanges();
            }
            return null;
 
        }
 
        // Update existing employee
        public JsonResult Update(int id,string name,string email,string address)
        {
            using (EmployeeContext contextObj = new EmployeeContext())
            {
                var employeeList = contextObj.EmployeeData.Where(x => x.Id ==  id).FirstOrDefault();
                employeeList.Name = name;
                employeeList.Email = email;
                employeeList.Address = address;
               
                contextObj.SaveChanges();
            }
            return null;
        }
 
        // Delete existing employee
        public JsonResult Delete(int id)
        {
            using (EmployeeContext contextObj = new EmployeeContext())
            {
                var employeeList = contextObj.EmployeeData.Where(x => x.Id == id).FirstOrDefault();
                contextObj.EmployeeData.Remove(employeeList);
                contextObj.SaveChanges();
            }
            return null;
        }
 

4. Change existing connection string or Add database connection in web.config.

<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=.\;Initial Catalog=SampleAngularMVCDb;Integrated Security=True;" providerName="System.Data.SqlClient" />
  </connectionStrings>

5. Go to Scripts and create a new folder as EmployeeScripts, under EmployeeScripts folder create 3 new js files as AngApp.js, EmpController.js & EmpService.js.

 

6. Now under shared folder there is view named _Layout.cshtm, add all these scripts files in that shared view.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>@ViewBag.Title - My ASP.NET MVC Application</title>
        <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
        <meta name="viewport" content="width=device-width" />
        @Styles.Render("~/Content/css")
        @Scripts.Render("~/bundles/modernizr")
        <script src="~/EmployeeScripts/js/angular.min.js"></script>
        <script src="~/EmployeeScripts/js/AngApp.js"></script>
        <script src="~/EmployeeScripts/js/EmpController.js"></script>
        <script src="~/EmployeeScripts/js/EmpService.js"></script>
    </head>
   <body>
….
</body>
</html>


7. Now let’s create view named Index.cshtml with AngularJS code under folder Home, then add ng-app,ng-controller,ng-model,ng-repeat,ng-click AnularJS directives in this view with required html code.

 @{
    ViewBag.Title = "Home Page";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<div ng-app="EmpApp" ng-controller="EmpCntrlr">
   
        <table border="1" cellpadding="10" align="center">
 
            <tr>
                <td colspan="4">
                    <form name="myForm" novalidate>
                        <table>
                            <tr>
                                <td>
                                    <input type="hidden" id="txtid" name="id" ng-model="employeeData.Id" />
                                </td>
                                <td>
                                    Name:
                                    <input type="text" id="txtEmpName" name="name" ng-model="employeeData.Name" />
                                </td>
                                <td>
                                    Email:
                                    <input type="email" id="txtEmpEmail" name="email" ng-model="employeeData.Email" />
                                    <span ng-show="myForm.email.$error.email">Invalid email address.</span>
                                </td>
                                <td>
                                    Address:
                                    <input type="text" id="txtEmpAddress" name="address" ng-model="employeeData.Address" />
                                </td>
                            </tr>
                            <tr>
                                <td colspan="3" style="text-align:right">
                                    <button ng-click="myForm.$valid && Save()">Save</button>
                                   
                                </td>
                            </tr>
                        </table>
                    </form>
          </td>
            </tr>
 
            <tr>
                <th>
                   
                </th>
                <th>
                    Name
                </th>
                <th>
                    Email
                </th>
                <th>
                    Address
                </th>
            </tr>
            <tr ng-repeat="emp in employees|orderBy :'Id'">
 
                <td>
                </td>
                <td>
                    <input type="text" id="txtName" ng-model="emp.Name" />
                </td>
                <td>
                    <input type="text" id="txtem" ng-model="emp.Email" />
                </td>
                <td>
                    <input type="text" id="txtadd" ng-model="emp.Address" />
                </td>
                <td>
                    <button ng-click="Delete(emp.Id)">Delete</button>
                </td>
                <td>
                    <button ng-click="Update(emp.Id,emp.Name,emp.Email,emp.Address)">Update</button>
                </td>
            </tr>
        </table>
</div>
 


8. Open AngApp.js and define angular module as below

var app = angular.module("EmpApp", []);

9. Open EmpService.js and define functions for CRUD (insert, update, delete) operations on Employee.

app.service("EmployeeService", function ($http) {
 
    // Get Employee data
    this.getEmployee = function () {
        debugger;
        return $http.get("/Home/GetAllEmployees");
    };
    // Delete Employee by Id
    this.DeleteEmployee = function (EmpID) {
        var response = $http({
            method: "post",
            url: "Home/Delete",
            params: {
                id: EmpID
            }
        });
        return response;
    }
    // Update Employee
    this.UpdateEmployee = function (Id, Name, Email, Address) {
        var response = $http({
            method: "post",
            url: "Home/Update",
            params: {
                id: Id, name: JSON.stringify(Name), email: JSON.stringify(Email), address: JSON.stringify(Address)
            }
        });
        return response;
    }
});

 

10.  Open EmpController.js and all required functions(i.e clear(),setdefaultdata() etc) with CRUD operations.

app.controller("EmpCntrlr", function ($scope, EmployeeService) {
    GetAllEmployee();
    function GetAllEmployee() {
        debugger;
        var getAllEmployee = EmployeeService.getEmployee();
        getAllEmployee.then(function (empls) {
            $scope.employees = empls.data;
        }, function () {
            alert('Employee data not found');
        });
    }
 
    $scope.employeeData= {
 
        id: 0,
 
        Name: 'nagnath',
 
        Email: 'test@gmail.com',
 
        Address: 'ok'
 
    }
 
    $scope.Save = function () {
        $.ajax({
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify($scope.employeeData),
            url: '/Home/Save',
            success: function (data, status) {
                ClearFields();
                GetAllEmployee();
            },
            error: function (status) { }
        });
    }
 
     // Angular ajax function deletes employee data for selected employee
       $scope.Delete = function (EmpId) {
        debugger;
        var DelEmployee = EmployeeService.DeleteEmployee(EmpId);
        DelEmployee.then(function (empls) {
            ClearFields();
            GetAllEmployee();
        }, function () {
            alert('Employee data not found');
        });
       }
    // Angular ajax function Update employee data for selected employee
       $scope.Update = function (Id,Name,Email,Address) {
           debugger;
           var UpdateEmployeeData = EmployeeService.UpdateEmployee(Id, Name, Email, Address);
           UpdateEmployeeData.then(function (empls) {
               ClearFields();
               GetAllEmployee();
           }, function () {
               alert('Employee data not found');
           });
       }
 
    function ClearFields() {
        $scope.Name = "";
        $scope.Email = "";
        $scope.Address = "";
      
    }
 
});
 

Final Page Look 


Comments (1) -

Invalid entry,please enter valid data.

Loading