Print Friendly and PDF
In this article I am going to explain how to insert, update, delete and show the data using AngularJs in asp.net MVC.
In this article, I am going to explain how to perform Crud Operation with AngularJs in asp.net MVC.

First Of All,  Create A Database with Name Testdb with following script copy and paste into SQL server.

Database Table 
USE [Testdb]
GO

/****** Object:  Table [dbo].[Employe]    Script Date: 9/16/2017 1:15:19 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[Employe](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Name] [varchar](50) NULL,
    [Phone] [int] NULL,
    [Salary] [int] NULL,
    [Department] [varchar](50) NULL,
    [EmailId] [varchar](50) NULL,
 CONSTRAINT [PK_Employe] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
 ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

After Creating Database we need to run the Visual Studio create a new empty MVC Project.Now first going to right-click on Models Folder and then Click addNew Item → Data→Select  ADO.Net Entity Data model after Completing the whole steps than import the Appropriate database into your project. 

Entity Data Model Look like this
namespace CrudApp.Models
{
    using System;
    using System.Collections.Generic;
    
    public partial class Employe
    {
        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; }
    }
}
After Completing the entity data model now time to create a controller into Controller folder with Name TechSpiderController.cs. 
First Adding the model reference into controller file in my case Model Name Look line this 
using CrudApp.Models;
TechSpiderController.cs

First, i am initializing the entity database connection into my controller file in my case I have a connection string name TestdbEntities that comes from web.config file 


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CrudApp.Models;
namespace CrudApp.Controllers
{
    public class TechSpiderController : Controller
    {

        TestdbEntities db = new TestdbEntities();

        // GET: Demo
        public ActionResult Index()
        {
            return View();
        }
}
}

Whole Source code of this Controller 


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CrudApp.Models;
namespace CrudApp.Controllers
{
    public class TechSpiderController : Controller
    {

        TestdbEntities db = new TestdbEntities();

        // GET: Demo
        public ActionResult Index()
        {
            return View();
        }

        public JsonResult GetEmployee()
        {
            var emp = db.Employes.ToList();
            return Json(emp, JsonRequestBehavior.AllowGet);


        }
        [HttpPost]
        public JsonResult InsertEmployee(Employe em)
        {
            db.Employes.Add(em);
            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.Employes.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)
        {
            Employe emp = db.Employes.Find(id);
            db.Employes.Remove(emp);
            db.SaveChanges();
            return Json(emp, JsonRequestBehavior.AllowGet);
        }
        [HttpGet]
        public JsonResult getByid(int id)
        {
            Employe emp = db.Employes.Find(id);
            return Json(emp, JsonRequestBehavior.AllowGet);
        }
    }
}

Now it's time to add view into your project right click on View in controller file and click  Add View→Save 

Index.chtml


@{ 
    ViewBag.Title = "Crud with AngularJs asp.net MVC";
}
<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>
<h2>AngularJs Tutorial : CRUD operation</h2> <div ng-app="myapp" ng-controller="TechSpiderController"> <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>
<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('mapp', []);

    angular.controller('TechSpiderController', 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>

If You have any confusion in this articles please feel free and discuss with us.





zubairsaif

Zubair saif

A passionate writer who loves to write on new technology and programming

Post A Comment:

0 comments: