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.

How to implement Angular Js UI-Grid in Asp.net MVC ?


UI-Grid is one of the most popular and stable open source angularJs Grid. It is completely written using angular js. It is very fast. It contains almost all the features which contains the commercial third party grid controls.

For more details, please go to this official site

http://ui-grid.info/

To implement in asp.net MVC, we can do like this

Step 1: Create the asp.net MVC application.

Step 2: Create the tblEmp with (Id,EmpName,EmpAddress,EmailId) field in database and keep some data for demo.

Step 3: Create the Emp Model class like this in Model folder

namespace UI_Grid_Sample.Models
{
    public class Emps
    {
        public int Id { get; set; }
        public string EmpName { get; set; }
        public string EmpAddress { get; set; }
        public string EmailId { get; set; }
        public string Operation { get; set; }
    }
}

Step 4: Create the Emp Controller using Asp.net Web API and Write the code to Fetch data from tblEmp like this



using System;
using System.Collections.Generic;
using System.Web.Http;
using System.Data.SqlClient;
using UI_Grid_Sample.Models;

namespace UI_Grid_Sample.Services
{
    public class EmpController : ApiController
    {
        const string sConnString = "Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\Database1.mdf;Integrated Security=True";

        List<Emps> MyEmps = new List<Emps>();
       

        [HttpPost]
        public IEnumerable<Emps> FetchBookList(Emps objList)
        {
            using (SqlConnection con = new SqlConnection(sConnString))
            {
                SqlCommand objComm = new SqlCommand("SELECT Id,EmpName,EmpAddress,EmailId FROM tblEmp", con);
                con.Open();

                SqlDataReader reader = objComm.ExecuteReader();

                while (reader.Read())
                {
                    MyEmps.Add(new Emps
                    {
                        Id = Convert.ToInt32(reader["Id"]),
                        EmpName = reader["EmpName"].ToString(),
                        EmpAddress = reader["EmpAddress"].ToString(),
                        EmailId =  reader["EmailId"].ToString()
                    });
                }
                con.Close();
            }

            return MyEmps;
        }

        
    }
}  

Step 5: Create One controller in asp.net MVC i.e. Emp

using System.Web.Mvc;

namespace UI_Grid_Sample.Controllers
{
    public class EmpController : Controller
    {
        //
        // GET: /Emp/

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

    }
}
 

Step 5: Create a view and add the reference for angularjs, UIGrid, UIGrid Css and write the code for consuming consuming Web API method in AngularJs as given below



@{
    ViewBag.Title = "Index";
}
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.js"></script>
 <script src="http://ui-grid.info/release/ui-grid.js"></script>
 <link rel="stylesheet" href="http://ui-grid.info/release/ui-grid.css" type="text/css">

   
    <style>
        p, div {
            font:15px Verdana;
        }
        .uiGrd {
            width: 580px;
            height: 200px;
        }
    </style>

<script type="text/javascript">
    var myApp = angular.module('myApp', ['ui.grid']);
    myApp.controller('myController',
        function ($scope, $http) {

            FetchEmpList('READ');

            function FetchEmpList(ops) {
                var request = {
                    method: 'post',
                    url: '/api/emp/',
                    data: {
                        Operation: ops
                    },
                    dataType: 'json',
                    contentType: "application/json"
                };

                $scope.arrEmps = new Array;

                // POST DATA WITH $http.
                $http(request)
                    .success(function (data) {
                        var i = 0;      // JUST A COUNTER.

                        // LOOP THROUGH EACH DATA.
                        angular.forEach(data, function () {
                            var b = {
                                EmpId: data[i].Id,
                                EmpName: data[i].EmpName,
                                EmpAddress: data[i].EmpAddress,
                                EmailId: data[i].EmailId
                            };

                            $scope.arrEmps.push(b);
                            i += 1;
                        });

                    })
                    .error(function () {

                    });

                $scope.gridData = { data: 'arrEmps' };
            };
        });

</script>

<h2>Sample code for AngularJs GridUI </h2>

<div ng-app="myApp"  ng-controller="myController">
       
        
        <div class="uiGrd" id="grd" ui-grid="gridData"></div>
</div>

 

How to create custom filter in AngularJs


Custom_Filter

We can create our own custom filter depending on our own requirement. Here I will show one of the simple and interesting custom filters in below example

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <script src="../Scripts/angular.js"></script>
    <script>
        var app = angular.module("MyApp", []);
        app.filter("reverse", function myfunction() {
            return function (input) {
                var result = "";
                 input = input || "";
                for (var i = 0; i < input.length; i++) {
                    result = input[i]+result;
                }
                return result;
            };
        });
    </script>
</head>
<body ng-app="MyApp">
    <div>
        <input type="text" name="name" ng-model="text" placeholder="Enter text" />
        <p>Input: {{text}}</p>
        <p>Filter Input :{{ text | reverse }}</p>
    </div>
</body>
</html>

Summary:
In this example we learnt to create the custom filter depending on our own requirement in angularJs.

How to implement pagination in AngularJs ?


Pagination

There are so many approaches to do pagination in angularJs. But using factory service approach is one of the easiest approaches to do pagination with Server side data.

Let see the step by step demo for this

Step1: Create one app.js file and write the code related with Consuming external service and Pagination related code as given below

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

//This service can be changed for real time data consumption. For simiplicity we have kept this code. 
app.factory("Item", function () {
    var items = [];
    for (var i = 1; i < 100; i++) {
        items.push({ id: i, name: "ProductName " + i, description: "Description " + i });
    }

    return {
        get: function (offset, limit) {
            return items.slice(offset, offset + limit);
        },
        total: function () {
            return items.length;
        }
    };
});

app.controller("PaginationCtrl", function ($scope, Item) {

    $scope.itemsPerPage = 5;
    $scope.currentPage = 0;

    $scope.range = function () {
        var rangeSize = 5;
        var ret = [];
        var start;

        start = $scope.currentPage;
        if (start > $scope.pageCount() - rangeSize) {
            start = $scope.pageCount() - rangeSize;
        }

        for (var i = start; i < start + rangeSize; i++) {
            ret.push(i);
        }
        return ret;
    };


    $scope.prevPage = function () {
        if ($scope.currentPage > 0) {
            $scope.currentPage--;
        }
    };

    $scope.prevPageDisabled = function () {
        return $scope.currentPage === 0 ? "disabled" : "";
    };

    $scope.nextPage = function () {
        if ($scope.currentPage < $scope.pageCount() - 1) {
            $scope.currentPage++;
        }
    };

    $scope.nextPageDisabled = function () {
        return $scope.currentPage === $scope.pageCount() - 1 ? "disabled" : "";
    };

    $scope.pageCount = function () {
        return Math.ceil($scope.total / $scope.itemsPerPage);
    };

    $scope.setPage = function (n) {
        if (n > 0 && n < $scope.pageCount()) {
            $scope.currentPage = n;
        }
    };

    $scope.$watch("currentPage", function (newValue, oldValue) {
        $scope.pagedItems = Item.get(newValue * $scope.itemsPerPage, $scope.itemsPerPage);
        $scope.total = Item.total();
    });

});

Step 2: Write the html code to render data and displaying pagination like given below

<!DOCTYPE html>
<html>
<head>
    <title></title>
	<meta charset="utf-8" />
    <script src="../Pagination/angular.js"></script>
    <script src="app.js"></script>
    <link href="../Style/bootstrap.css" rel="stylesheet" />

</head>
<body ng-app="MyApp">
    <div ng-controller="PaginationCtrl">
        <table class="table table-striped">
            <thead>
                <tr>
                    <th>Id</th>
                    <th>ProductName</th>
                    <th>Description</th>
                </tr>
            </thead>
            <tbody>
                <tr ng-repeat="item in pagedItems">
                    <td>{{item.id}}</td>
                    <td>{{item.name}}</td>
                    <td>{{item.description}}</td>
                </tr>
            </tbody>
            <tfoot>
            <td colspan="3">
                <div class="pagination">
                    <ul>
                        <li ng-class="prevPageDisabled()">
                            <a href ng-click="prevPage()">« Prev</a>
                        </li>
                        <li ng-repeat="n in range()" ng-class="{active: n == currentPage}" ng-click="setPage(n)">
                            <a href="#">{{n+1}}</a>
                        </li>
                        <li ng-class="nextPageDisabled()">
                            <a href ng-click="nextPage()">Next »</a>
                        </li>
                    </ul>
                </div>
            </td>
            </tfoot>
        </table>
    </div>
</body>
</html>

Summary:

Here we saw that how to implement basic pagination functionality in AngularJs.

Validation with Bootstrap in AngularJs


Validation_With_Bootstrap

We can make very interactive UI validation with help of Bootstrap in AngularJs Framework. Here I will show one simple validation example with bootstrap in angularJs.

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <script src="../Scripts/angular.js"></script>
    <link href="../Style/bootstrap.css" rel="stylesheet" />
    <script>
        var app = angular.module("MyApp", []);
        app.controller("User", function ($scope) {
            $scope.error = function (name) {
                var s = $scope.form[name];
                return s.$invalid && s.$dirty ? "error" : "";
            };
        });
    </script>
</head>
<body ng-app="MyApp">
    <div ng-controller="User">
        <br />
        <form name="form" ng-submit="submit()" class="form-horizontal">
            <div class="control-group" ng-class="error('FirstName')">
                <label class="control-label" for="FirstName">FirstName</label>
                <div class="controls">
                    <input id="FirstName" name="FirstName" type="text"
                           ng-model="User.FirstName" placeholder="FirstName" required />
                    <span class="help-block" ng-show="form.FirstName.$invalid && form.FirstName.$dirty">
                      First Name is required.
                    </span>
                </div>

            </div>
            <div class="control-group" ng-class="error('LastName')">
                <label class="control-label" for="LastName">LastName</label>
                <div class="controls">
                    <input id="LastName" name="LastName" type="text"
                           ng-model="User.LastName" placeholder="LastName" required />
                    <span class="help-block" ng-show="form.LastName.$invalid && form.LastName.$dirty">
                        Last Name is required.
                    </span>
                </div>
            </div>
            <div class="control-group" ng-class="error('Address')">
                <label class="control-label" for="Address">Address</label>
                <div class="controls">
                    <input id="Address" name="Address" type="text"
                           ng-model="User.Address" placeholder="Address" required />
                    <span class="help-block" ng-show="form.Address.$invalid && form.Address.$dirty">
                        Address is required.
                    </span>
                </div>
            </div>
            
            <div class="control-group">
                <div class="controls">
                    <button ng-disabled="form.$invalid" class="btn">Submit</button>
                </div>
            </div>

            
        </form>
    </div>
</body>
</html>

Summary:

In this post we learnt that how to do validation with Bootstrap in angularJs