CRUD operations using angular js and asp.net mvc

Hi everyone again in this tutorial i am going to explain CRUD(Create,Read,Update,Delete) operations using Angular js and asp.net mvc.In previous article crud operations using angular js and web api we performed create,read,update and delete operations using web api and angular js. In current article we will do the same with asp.net mvc. Please click on below link to for related articles on angular js Learning angular js with asp.net mvc.


Here in this tutorial the code is almost similar to previous article crud operations using angular js and web api. But,in current article instead of using web api calls we are using mvc controller.Remaining client and server communication is similar for both web api and mvc.
Related posts on crud operations are as follows,

CRUD operations using angular js and asp.net mvc

1.Create a asp.net mvc web application in visual studio 2015.
2.Add sql express data base to project in App_Data folder and create a table with below sql script.

CREATE TABLE [dbo].[Employee] (
    [EmpNo]       INT           IDENTITY (1, 1) NOT NULL,
    [EmpName]     NVARCHAR (50) NOT NULL,
    [Salary]      INT           NOT NULL,
    [DeptName]    NVARCHAR (50) NOT NULL,
    [Designation] NVARCHAR (50) NOT NULL,
    PRIMARY KEY CLUSTERED ([EmpNo] ASC)
);

3.Add ADO.NET Entity DataModel to models folder.
4.Add Controller to Controllers folder and name it as HomeController.
5.Replace controller code with below code.

using System.Data;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using WebAPICRUDwithBootstrap.Models;

namespace WebAPICRUDwithBootstrap.Controllers
{
    public class HomeController : Controller
    {
        private DatabaseEntities1 db = new DatabaseEntities1();
        public ActionResult Index()
        {
            return View();
        }

        public JsonResult GetEmployees()
        {
            return Json(db.Employees.ToList(), JsonRequestBehavior.AllowGet);
        }
        // GET: Employees/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Employee employee = db.Employees.Find(id);
            if (employee == null)
            {
                return HttpNotFound();
            }
            return Json(employee,JsonRequestBehavior.AllowGet);
        }

        // POST: Employees/Create
        [HttpPost]
        public ActionResult Create(Employee employee)
        {
            if (ModelState.IsValid)
            {
                db.Employees.Add(employee);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(employee);
        }

        // POST: Employees/Edit/5
        public ActionResult Edit(Employee Employee)
        {
            if (ModelState.IsValid)
            {
                db.Entry(Employee).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(Employee);
        }

        // POST: Employees/Delete/5
        public ActionResult Delete(int id)
        {
            Employee employee = db.Employees.Find(id);
            db.Employees.Remove(employee);
            db.SaveChanges();
            return Json(employee,JsonRequestBehavior.AllowGet);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}



6.Now add three script files Controller.js,module.js and Service.js files in scripts folder.
Module.js: Creates an angular module(a module contains controller to perform some actions).

//It acts as a auto bootstraper for angular application.
//We bind this module to view using ng-app directive.
var myapp;
(function () {
    myapp = angular.module('myangularapp', []);
})();

7.Controller.js: It is responsible for all logical operations in angular for example two way data binding.

//Angular controller 
myapp.controller('crudcontroller', function ($scope, crudservice) {
    
    //Loads all Employee records when page loads
    loadEmployees();
    function loadEmployees() {
        var EmployeeRecords = crudservice.getAllEmployees();
        EmployeeRecords.then(function (d) {     //success
            $scope.Employees = d.data;
        },
        function(){
            swal("Oops..","Error occured while loading","error"); //fail
        });
    }

    //save form data
    $scope.save = function () {
        var Employee = {
            EmpNo:$scope.EmpNo,
            EmpName: $scope.EmpName,
            Salary: $scope.Salary,
            DeptName: $scope.DeptName,
            Designation: $scope.Designation
        };
        var saverecords = crudservice.save(Employee);
        saverecords.then(function (d) {
            $scope.EmpNo = d.data.EmpNo;
            loadEmployees();
            swal("Reord inserted successfully");
        },
        function(){
            swal("Oops..","Error occured while saving",'error');
        });
    }

    //get single record by ID

    $scope.get = function (Employee) {
        var singlerecord = crudservice.get(Employee.EmpNo);
        singlerecord.then(function (d) {
            var record = d.data;
            $scope.UpdateEmpNo = record.EmpNo;
            $scope.UpdateEmpName = record.EmpName;
            $scope.UpdateSalary = record.Salary;
            $scope.UpdateDeptName = record.DeptName;
            $scope.UpdateDesignation = record.Designation;
        },
        function(){
            swal("Oops...","Error occured while getting record","error");
        });
    }

    //update Employee data
    $scope.update = function () {
        var Employee = {
            EmpNo: $scope.UpdateEmpNo,
            EmpName: $scope.UpdateEmpName,
            Salary: $scope.UpdateSalary,
            DeptName: $scope.UpdateDeptName,
            Designation:$scope.UpdateDesignation
        };
        var updaterecords = crudservice.update($scope.UpdateEmpNo, Employee);
        updaterecords.then(function (d) {
            loadEmployees();
            swal("Record updated successfully");
        },
        function () {
            swal("Opps...","Error occured while updating","error");
        });
    }

    //delete Employee record
    $scope.delete = function (UpdateEmpNo) {
        var deleterecord = crudservice.delete($scope.UpdateEmpNo);
        deleterecord.then(function (d) {
            var Employee = {
                EmpNo: '',
                EmpName: '',
                Salary: '',
                DeptName: '',
                Designation: ''
            };
            loadEmployees();
            swal("Record deleted succussfully");
        });
    }
});



8.Service.js: It is responsible for communication between controller and server(uses $http service).

//Service to get data from service..
myapp.service('crudservice', function ($http) {
    
    this.getAllEmployees = function () {
        return $http.get("http://localhost:56193/Home/GetEmployees");
    }

    //save
    this.save = function (Employee) {
        var request = $http({
            method: 'post',
            url: 'http://localhost:56193/Home/Create',
            data:Employee
        });
        return request;
    }

    //get single record by Id
    this.get = function (EmpNo) {
        return $http({
            method: 'get',
            url: 'http://localhost:56193/Home/Details?id=' + EmpNo,
            data: JSON.stringify(EmpNo)
        });
    };

    //update Employee records
    this.update = function (UpdateEmpNo, Employee) {
        var updaterequest = $http({
            method: 'post',
            url: "http://localhost:56193/Home/Edit",
            data:Employee
        });
        return updaterequest;
    }

    //delete record
    this.delete = function (UpdateEmpNo) {
        var deleterecord= $http({
            method: 'delete',
            url: "http://localhost:56193/Home/Delete?id=" + UpdateEmpNo
        });
        return deleterecord;
    }
});

9.The final output of the application is look like below.

CRUD operations using angular js and asp.net mvc



10.I hope this article may help you.Download source code for this application from here Download.

CRUD operations using angular js and asp.net mvc CRUD operations using angular js and asp.net mvc Reviewed by raviteja swayampu on 02:19:00 Rating: 5

No comments: