How to do CRUD operation in Asp.net MVC using AngularJs


Hi All,

In this post, we will see how to do CRUD(Create/Read/update/Delete) operation with database in Asp.net MVC using AngularJs and Bootstrap.

Step 1: Create the Empty MVC application.

Step 2: Right click on project and Go to the “Manage Nuget Package” and Install the Angularjs like this

Step 3: Create the database in application and add the tblDept table like this

Step 4: Go to the Model folder and Add the EntityFramework Model and map the table like this

Step 5: Go to the Controller folder and Add the Empty Dept Controller and write the code for doing Insert/Update/Delete/Fetch functionality like this.

using AngularCRUD.Models;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

namespace AngularCRUD.Controllers
{
    public class DeptController : Controller
    {
        // GET: /Dept/

        public ActionResult Index()
        {
            return View();
        }

        public JsonResult Get_AllDepts()
        {
            using (Database1Entities obj = new Database1Entities())
            {
                List<tblDept> objDept = obj.tblDepts.ToList();
                return Json(objDept, JsonRequestBehavior.AllowGet);
            }
        }

        public JsonResult Get_DeptById(string Id)
        {
            using (Database1Entities obj = new Database1Entities())
            {
                int DeptId = int.Parse(Id);
                return Json(obj.tblDepts.Find(DeptId), JsonRequestBehavior.AllowGet);
            }
        }

        public string Insert_Dept(tblDept dept)
        {
            if (dept != null)
            {

                using (Database1Entities obj = new Database1Entities())
                {
                    obj.tblDepts.Add(dept);
                    obj.SaveChanges();
                    return "Dept details Added Successfully";
                }
            }
            else
            {
                return "Dept Details Not Inserted! Try Again";
            }

        }

        public string Update_Dept(tblDept Dept)
        {
            if (Dept != null)
            {
                using (Database1Entities Obj = new Database1Entities())
                {
                    tblDept DeptObj = Obj.tblDepts.Find(Dept.Id); 
                    ////tblDept DeptObj = Obj.tblDepts.Where(x => x.Id == Dept.Id).FirstOrDefault();
                    DeptObj.DeptName = Dept.DeptName;
                    DeptObj.DeptDesc = Dept.DeptDesc;
                   
                    Obj.SaveChanges();
                    return "Dept details Updated Successfully";
                }
            }
            else
            {
                return "Dept Details Not Updated! Try Again";
            }
        }  

        public string Delete_Dept(tblDept dept) 
        {
            if (dept != null)
            {

                using (Database1Entities obj = new Database1Entities())
                {
                    //one approach to find the object Entity by Id
                    tblDept DeptObj = obj.tblDepts.Find(dept.Id); 

                    //Other approach find the object entity by Id
                   // tblDept DeptObj = obj.tblDepts.Where(x => x.Id == dept.Id ).FirstOrDefault();
                    
                    obj.tblDepts.Remove(DeptObj);
                    obj.SaveChanges();
                    return "Dept details deleted Successfully";
                }
            }
            else
            {
                return "Dept Details Not Deleted! Try Again";
            }
        }
    }
}

Step 6: Go to the Script folder and create Myscript folder and Add angularDept.js file write the code for calling Json action method from Controller like this

/// <reference path="../angular.min.js" />
var app = angular.module("DemoApp", []);

app.controller("DeptController", function ($scope, $http) {
    $scope.InsertData = function () {
        var action = document.getElementById("btnSave").getAttribute("value");
        if (action == "Submit") {
            debugger;
            $scope.Dept = {};
            $scope.Dept.DeptName = $scope.DeptName;
            $scope.Dept.DeptDesc = $scope.DeptDesc;
            $http({
                method: "post",
                url: "http://localhost:51374/Dept/Insert_Dept",
                datatype: "json",
                data: JSON.stringify($scope.Dept)
            }).then(function (response) {
                $scope.GetAllData();
                $scope.DeptName = "";
                $scope.DeptDesc = "";

            }, function () {
                alert("Error Occur");
            });
        }
        else {
            debugger;
            $scope.Dept = {};
            $scope.Dept.DeptName = $scope.DeptName;
            $scope.Dept.DeptDesc = $scope.DeptDesc;
            $scope.Dept.Id = document.getElementById("DeptID_").value;
            console.log($scope.Dept.Id);
            $http({
                method: "post",
                url: "http://localhost:51374/Dept/Update_Dept",
                datatype: "json",
                data: JSON.stringify($scope.Dept)
            }).then(function (response) {
                alert(response.data);
                $scope.GetAllData();
                $scope.DeptName = "";
                $scope.DeptDesc = "";
                document.getElementById("btnSave").setAttribute("value", "Submit");
                document.getElementById("btnSave").style.backgroundColor = "cornflowerblue";
                document.getElementById("spn").innerHTML = "Add New Dept Details";
            }, function () {
                alert("Error Occur");
            })

        }
    }

    //This is for fetching data from database.
    $scope.GetAllData = function () {
        debugger;
        $http({
            method: "get",
            url: "http://localhost:51374/Dept/Get_AllDepts"
        }).then(function (response) {
            $scope.Depts = response.data;
            console.log(response.data);
        }, function () {
            alert("Error Occur");
        })

    };

    //This is for deleting the record.
    $scope.DeleteDept = function (Dept) {
        $http({
            method: "post",
            url: "http://localhost:51374/Dept/Delete_Dept",
            datatype: "json",
            data: JSON.stringify(Dept)
        }).then(function (response) {
            alert(response.data);
            $scope.GetAllData();
        }, function () {
            alert("Error Occur");
        })
    };


    //This is for selecting record on clicking particular record.
    $scope.UpdateDept = function (Dept) {
        debugger;
        document.getElementById("DeptID_").value = Dept.Id;
        $scope.DeptName = Dept.DeptName;
        $scope.DeptDesc = Dept.DeptDesc;
        document.getElementById("btnSave").setAttribute("value", "Update");
        document.getElementById("btnSave").style.backgroundColor = "Yellow";
        
    };

});

Step 7: Create the Empty View from Dept Controller and write the binding code like this

@{
    ViewBag.Title = "Index";
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div>
    <form data-ng-app="DemoApp" data-ng-controller="DeptController" ng-submit="InsertData()" data-ng-init="GetAllData()"  name="myForm" novalidate >
      <br />
        <br />
        <div class="container">
        <div class="panel panel-primary">
      <div class="panel-heading">Dept List</div>
      <div class="panel-body">
           <table cellpadding="12" class="table table-bordered table-hover">
            <tr>
                <td>
                    <b>ID</b>
                </td>
                <td>
                    <b>DeptName</b>
                </td>
                <td>
                    <b>Decscription</b>
                </td>
                
                <td>
                    <b>Actions</b>
                </td>
            </tr>
            <tr data-ng-repeat="dept in Depts">
                <td>{{dept.Id}}  
                </td>
                <td>{{dept.DeptName}}  
                </td>
                <td>{{dept.DeptDesc}}  
                </td>
                
                <td>
                    <input type="button" class="btn btn-warning" value="Update" data-ng-click="UpdateDept(dept)" />
                    <input type="button" class="btn btn-danger" value="Delete" data-ng-click="DeleteDept(dept)" />
                </td>
            </tr>
        </table>
          </div>
       </div>
      </div> 
       <div class="container">
        <div class="panel panel-primary">
      <div class="panel-heading">Dept Entry Screen</div>
      <div class="panel-body">
        <div class="form-horizontal" role="form">
            <div class="container">
                <div class="row">
                    <div class="col-sm-6 col-lg-4">
                        <div class="form-group">
                            <label class="col-md-4 control-label">Dept Name:</label>
                            <div class="col-md-8">
                                <input type="text" name="name"  placeholder="Name" data-ng-model="DeptName" data-ng-required="true" >
                                 <span ng-show="myForm.$submitted || myForm.name.$touched">
                              <span style="color:red" ng-show="myForm.name.$error.required">Name Required</span>
                              </span>
                            </div>
                        </div>
                    </div>
                    <div class="col-sm-6 col-lg-4">
                        <div class="form-group">
                            <label class="col-md-4 control-label">Dept Desc:</label>
                            <div class="col-md-8">
                                <input type="text"  id="inputDeptDesc" required placeholder="Description" name="DeptDesc" data-ng-model="DeptDesc">
                                <span ng-show="myForm.$submitted || myForm.DeptDesc.$touched">
                              <span style="color:red" ng-show="myForm.DeptDesc.$error.required">Desc Required</span>
                              </span>
                            </div>
                        </div>
                    </div>
                   
                    <div class="col-sm-6 col-lg-4">
                        <div class="form-group">
                            <div class="col-md-4 control-label"></div>
                            <div class="col-md-6">
                                 <input type="submit" value="Submit" id="btnSave" class="btn btn-info" data-ng-disabled=" myForm.name.$invalid ||myForm.DeptDesc.$invalid " />
                            </div>
                        </div>
                    </div>
                </div>
               
            </div>
        </div>
          </div>
    
    @Html.Hidden("DeptID_")

 </div>
 </div>
 </form> 
        
</div>

Step 8: Go to the BundleConfig.cs file and Include the Javascript Angular file like this

Step 9: Go to the _Layout.cshtml file and include the bundles file like this

Step 10: Now run the application, you will get the above output.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.