ANGULAR JS WITH MVC INSERT,UPDATE, DELETE

Ankit Singh

Total Post:341

Points:2389
Posted by  Ankit Singh
 1340  View(s)
Ratings:
Rate this:
I want to use Angularjs  in  MVC for Insert,Update, Delete .How to use Angularjs  with database please help me. 
  1. aditya kumar Patel

    Post:254

    Points:1810
    Re: Angular js with MVC Insert,Update, Delete

    Hi Ankit,
    Here , we are  choosing  Database Model shown is below:

    CREATE TABLE Employee
    (
    Id int Not Null primary key,
    name nvarchar(50),
    email nvarchar(50),
    mobile_no nvarchar(50)
    )

    Home Controller:

    using System;

    using System.Linq;

    using System.Web.Mvc;

    namespace ForumMVC.Controllers

    {

        public class HomeController : Controller

        {     

            public ActionResult Index()

            {

                return View();

            }

            public JsonResult getAll()

            {

                using (Entities dataContext = new Entities())

                {

                    var employeeList = dataContext.Employee.ToList();

                    return Json(employeeList, JsonRequestBehavior.AllowGet);

                }

            }

            public JsonResult getEmployeeByNo(string EmpNo)

            {

                using (Entities dataContext = new Entities())

                {

                    int no = Convert.ToInt32(EmpNo);

                    var employeeList = dataContext.Employee.Find(no);

                    return Json(employeeList, JsonRequestBehavior.AllowGet);

                }

            }

            public string UpdateEmployee(Employee Emp)

            {

                if (Emp != null)

                {

                    using (Entities dataContext = new Entities())

                    {

                        int no = Convert.ToInt32(Emp.Id);

                        var employeeList = dataContext.Employee.Where

                        (x => x.Id == no).FirstOrDefault();

                        employeeList.name = Emp.name;

                        employeeList.mobile_no = Emp.mobile_no;

                        employeeList.email = Emp.email;

                        dataContext.SaveChanges();

                        return "Employee Updated";

                    }

                }

                else

                {

                    return "Invalid Employee";

                }

            }

            public string AddEmployee(Employee Emp)

            {

                if (Emp != null)

                {

                    using (Entities dataContext = new Entities())

                    {

                        dataContext.Employee.Add(Emp);

                        dataContext.SaveChanges();

                        return "Employee Updated";

                    }

                }

                else

                {

                    return "Invalid Employee";

                }

            }

            public string DeleteEmployee(Employee Emp)

            {

                if (Emp != null)

                {

                    using (Entities dataContext = new Entities())

                    {

                        int no = Convert.ToInt32(Emp.Id);

                        var employeeList = dataContext.Employee.Where

                        (x => x.Id == no).FirstOrDefault();

                        dataContext.Employee.Remove(employeeList);

                        dataContext.SaveChanges();

                        return "Employee Deleted";

                    }

                }

                else

                {

                    return "Invalid Employee";

                }

            }

        }

    }

     

    View: Index.cshtml

    <!DOCTYPE html>

    <html ng-app="myApp">

    <head>

        <meta name="viewport" content="width=device-width" />

        <title>Index</title>

        <script src="~/Scripts/jquery-1.9.1.min.js"></script>

        <link href="~/Content/bootstrap.css" rel="stylesheet" />

        <script src="~/Scripts/bootstrap.min.js"></script>

        <script src="~/Scripts/angular.js"></script>

        <script src="~/Scripts/Model.js"></script>

        <script src="~/Scripts/service.js"></script>

        <script src="~/Scripts/controller.js"></script>

        <style>

            .modal-dialog {

        width: 600px;

        margin: 15% auto !important;

    }

        </style>

    </head>

    <body>

        <div class="container">

            <div ng-controller="myCntrl">

                <div class="panel panel-default">

                    <div class="panel-heading">

                        <div class="panel-title"><h3> Employee Details Page</h3></div>

                        <div style="float: right; font-size: 80%; position:inherit; top: auto">

                           <input type="button" class="btnAdd btn btn-success"

                           value=" New One" id="NewDiv"/></div>

                        <div style="float: right; font-size: 80%; position: relative; top: -29px">

                             <input type="button" class="btnAdd btn btn-success"

                         value=" Add Employee" ng-click="AddEmployeeDiv()" /></div>

                         

                    </div>

                    <div style="padding-top: 30px" class="panel-body">

     

                        <div class="divList">

                            <p class="divHead">Employee List</p>

                            <table cellpadding="12" class="table table-bordered table-hover">

                                <tr>

                                    <td><b>ID</b></td>

                                    <td><b>Name</b></td>

                                    <td><b>Email</b></td>

                                    <td><b>Age</b></td>

                                    <td><b>Actions</b></td>

                                </tr>

                                <tr ng-repeat="employee in employees">

                                    <td>{{employee.Id}}

                                    </td>

                                    <td>{{employee.name}}

                                    </td>

                                    <td>{{employee.email}}

                                    </td>

                                    <td>{{employee.mobile_no}}

                                    </td>

                                    <td>  

                      <span ng-click="editEmployee(employee)" style="cursor: pointer;color:#0746D4;"

                        class="btnAdd btn btn-default btn-xs">Edit</span>

                   <span ng-click="deleteEmployee(employee)" style="cursor: pointer;color:#0746D4;"   class="btnRed btn btn-default btn-xs">Delete</span>

                                    </td>

                                </tr>

                            </table>

                        </div>

                            <div class="container">

                            <div class="col-md-12">

                                <div ng-show="divEmployee">

                                    <p class="divHead">{{Action}} Employee</p>

                                    <table >

                                        <tr>

                                            <td style=" padding-right:5px;"><b>Id</b></td>

                                            <td style=" padding-right:5px;">

                                            <input type="text" class="form-control"             ng-model="employeeId" />

                                            </td>

                                             <td style=" padding-right:5px;"><b>Name</b></td>

                                            <td style=" padding-right:5px;">

                                                <input type="text" class="form-control" ng-model="employeeName" />

                                            </td>

                                             <td style=" padding-right:5px;"><b>Email</b></td>

                                            <td style=" padding-right:5px;">

                                                <input type="text" class="form-control" ng-model="employeeEmail" />

                                            </td>

                                             <td style=" padding-right:5px;"><b>Mobile No</b></td>

                                            <td style=" padding-right:5px;">

                                                <input type="text" class="form-control" ng-model="employeemobile_no" />

                                            </td>

                                        </tr>   

                                     

                                        <tr>

                                            <td colspan="8" style="padding-top: 20px; text-align:right;">

                                                 <input type="button" class="btnAdd btn btn-default" value="Cancel" ng-click="Close()" />

                                                <input type="button" class="btnAdd btn btn-primary" value="Save" ng-click="AddUpdateEmployee()" />

                                            </td>

                                        </tr>

                                    </table>

                                </div>

                            </div>

                        </div>              

                    </div>

                </div>

            </div>

        </div> 

        <div class="modal fade" id="alertmodal" tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true">

      <div class="modal-dialog">

           <div class="modal-content">

                  <div class="modal-header" style="background-color: #ccc;">

                         <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>

                         <h3 class="modal-title" id="lineModalLabel">Alert</h3>

                  </div>

                  <div class="modal-body" id="alertcontent">

                  </div>

                  <div class="modal-footer" style="padding:0px;">

                         <div class="btn-group btn-group-justified" role="group" aria-label="group button">

                               <div class="btn-group" role="group">

                                      <button type="button" id="OK" class="btn btn-default " ng-click="OK()" style="border-radius: 0px 0px 0px 0px;border: 0px;" data-dismiss="modal"  role="button">OK</button>

                               </div>                    

                         </div>

                  </div>

           </div>

      </div>

    </div> 

    </body> 

    </html>

     
    Model.js

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

    Service.js:


    app.service("myService", function ($http) {

        //get All Eployee

        this.getEmployees = function () {

            debugger;

            return $http.get("Home/GetAll");

        };

        // get Employee By Id

        this.getEmployee = function (employeeID) {

            var response = $http({

                method: "post",

                url: "Home/getEmployeeByNo",

                params: {

                    id: JSON.stringify(employeeID)

                }

            });

            return response;

        }

        // Update Employee

        this.updateEmp = function (employee) {

            var response = $http({

                method: "post",

                url: "Home/UpdateEmployee",

                data: JSON.stringify(employee),

                dataType: "json"

            });

            return response;

        }

        // Add Employee

        this.AddEmp = function (employee) {

            var response = $http({

                method: "post",

                url: "Home/AddEmployee",

                data: JSON.stringify(employee),

                dataType: "json"

            });

            return response;

        } 

        //Delete Employee

        this.DeleteEmp = function (employee) {

            var response = $http({

                method: "post",

                url: "Home/DeleteEmployee",

                dataType: "json",

                data: JSON.stringify(employee),

            });

            return response;

        }

    });

    Controller.js:


    app.controller("myCntrl", function ($scope, myService) {

        $scope.divEmployee = false;

        GetAllEmployee();

        //To Get All Records

        function GetAllEmployee() {

            debugger;

            var getData = myService.getEmployees();

            debugger;

            getData.then(function (emp) {

                $scope.employees = emp.data;

            }, function () {

                $('#alertcontent').html('Error in getting record');

                $('#alertmodal').modal("show");        

            });

        } 

        $scope.editEmployee = function (employee) {

            debugger;

            var getData = myService.getEmployee(employee.Id);

            getData.then(function (emp) {

                $scope.employee = emp.data;

                $scope.employeeId = employee.Id;

                $scope.employeeName = employee.name;

                $scope.employeeEmail = employee.email;

                $scope.employeemobile_no = employee.mobile_no;

                $scope.Action = "Update";

                $scope.divEmployee = true;

            },

            function () {

                $('#alertcontent').html('Error in getting record');

                $('#alertmodal').modal("show");         

            });

        }

        $scope.AddUpdateEmployee = function () {

            debugger;

            var Employee = {

                Name: $scope.employeeName,

                Email: $scope.employeeEmail,

                mobile_no: $scope.employeemobile_no,

                Id: $scope.employeeId

            };

            var getAction = $scope.Action;

     

            if (getAction == "Update") {

                Employee.Id = $scope.employeeId;

                var getData = myService.updateEmp(Employee);

                getData.then(function (msg) {

                    GetAllEmployee();

                    $('#alertcontent').html(msg.data);

                    $('#alertmodal').modal("show");

                   

                    $scope.divEmployee = false;

                }, function () {

                    $('#alertcontent').html('Error in updating record');

                    $('#alertmodal').modal("show");

                  

                });

            } else {

                var getData = myService.AddEmp(Employee);

                getData.then(function (msg) {

                    GetAllEmployee();

                    $('#alertcontent').html(msg.data);

                    $('#alertmodal').modal("show");             

                    $scope.divEmployee = false;

                }, function () {

                    $('#alertcontent').html('Error in adding record');

                    $('#alertmodal').modal("show");          

                });

            }

        }

        $scope.AddEmployeeDiv = function () {

            ClearFields();

            $scope.Action = "Add";

            $scope.divEmployee = true;

        } 

        $scope.deleteEmployee = function (employee) {

            debugger;

            var getData = myService.DeleteEmp(employee);

            getData.then(function (msg) {

                GetAllEmployee();

                $('#alertcontent').html('Employee Deleted');

                $('#alertmodal').modal("show");

              

            }, function () {         

                $('#alertcontent').html('Error in Deleting Record');

                $('#alertmodal').modal("show");

            });

        } 

        $scope.Close = function () {

            ClearFields();

            $scope.divEmployee = false;

        }

        function ClearFields() {

            $scope.employeeId = "";

            $scope.employeeName = "";

            $scope.employeeEmail = "";

            $scope.employeemobile_no = "";

        }

    });

    Output:

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!