AngularJS CRUD Operation in ASP.NET MVC

 Print 
 Posted By :  ASPArticles
 Posted Date: Jun 30, 2018
 Category :  ,
 Post Hits : 442

In this article, I am going to explain you how to perform CRUD operation (Create, Read, Update and Delete) using AngularJS with ASP.NET MVC. We will be using Visual Studio 2013.

Creating Database Table

We will be using tblEmployee table for database operation. Use below script to create table.

create table tblEmployee
(
ID int primary key identity,
Name varchar(100),
Gender varchar(20),
Salary varchar(100)
)

Creating Procedure

Create below procedure for CRUD operation.

create proc uspAngularCRUD
@ID int=null,
@Name varchar(100)=null,
@Gender varchar(20)=null,
@Salary varchar(100)=null,
@Task varchar(100)=null
as
begin

if(@Task='Select')
begin
      select * from tblEmployee
end
else if(@Task='Insert')
begin
      if(@ID is null)
      begin
              insert into tblEmployee(Name,Gender,Salary) values(@Name,@Gender,@Salary)
      end
      else
      begin
      update tblEmployee set Name=@Name,Gender=@Gender,Salary=@Salary where ID=@ID
      end
end
else if(@task='Delete')
begin
      delete from tblEmployee where ID=@ID
end
end

Creating ASP.NET MVC Empty Application

Now the next step is to create ASP.NET MVC empty application as shown below.
Go to FileNewProject. A new window will be open as shown below.
Now go to Web and select .NET Framework 4.5 and give project name and click on OK .

Creating asp.net mvc 5 application

Now new window will open as shown below.
Now Select Empty Template, check on MVC checkbox and click on OK.

Selecting asp.net mvc 5 empty template

Now, a new project will be created as shown below.

Asp.net mvc 5 empty folder structure

Adding Models

Go to Models folder and add new class file Employee.cs. Now replace all code with below code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication1.Models
{
    public class Employee
    {
        public int? ID { get; set; }
        public string Name { get; set; }
        public string Gender { get; set; }
        public string Salary { get; set; }
    }
}

Adding Data Access Layer

Create a Repository.cs class file in root directory of application. Add below code. Here, we have three methods GetAllEmployees() to fetch employee records, SaveEmployee() to save employee details and DeleteEmployee() to delete employee record.

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using WebApplication1.Models;

namespace WebApplication1
{
    public class Repository
    {
        public IEnumerable<Employee > GetAllEmployees()
        {
            // fetching connection string from web.config file
            // you can also use Entity Framework or Dapper ORM to fetch data from database
            List<Employee> empList = null;
            try
            {
                using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCS"].ToString()))
                {
                    empList = new List<Employee>();
                    SqlCommand cmd = new SqlCommand("uspAngularCRUD" , con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue( "@Task", "Select");
                    con.Open();
                    SqlDataReader sdr = cmd.ExecuteReader();
                    while (sdr.Read())
                    {
                        Employee e = new Employee();
                        e.ID = Convert.ToInt32(sdr["ID"].ToString());
                        e.Name = sdr[ "Name"].ToString();
                        e.Gender = sdr[ "Gender"].ToString();
                        e.Salary = sdr[ "Salary"].ToString();
                        empList.Add(e);
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return empList;
        }
        public bool SaveEmployee(Employee obj)
        {
            using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCS"].ToString()))
            {
                try
                {
                    SqlCommand cmd = new SqlCommand("uspAngularCRUD" , con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue( "@Task", "Insert");
                    cmd.Parameters.AddWithValue( "@Name", obj.Name);
                    cmd.Parameters.AddWithValue( "@Gender", obj.Gender);
                    cmd.Parameters.AddWithValue( "@Salary", obj.Salary);
                    con.Open();
                    if (obj.ID == null)
                    {
                        cmd.Parameters.AddWithValue( "@ID", null);
                    }
                    else
                    {
                        cmd.Parameters.AddWithValue( "@ID", obj.ID);
                    }

                    int output = cmd.ExecuteNonQuery();
                    //  int output = con.Execute("AngularCRUD", paramater, null, 0, CommandType.StoredProcedure);

                    return true;
                }
                catch (Exception ex)
                {
                    return false;
                }

            }
        }
        public bool DeleteEmployee(int ID)
        {
            using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCS"].ToString()))
            {
                try
                {
                    SqlCommand cmd = new SqlCommand("uspAngularCRUD" , con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue( "@Task", "Delete");
                    cmd.Parameters.AddWithValue( "@ID", ID);
                    con.Open();
                    int output = cmd.ExecuteNonQuery();
                    return true;
                }
                catch (Exception ex)
                {
                    return false;
                }
            }
        }
    }
}

Adding Controller

Next step is to add controller to application. Go to controller folder and add new empty controller named as Home controller. Replace all code with below code.

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

namespace WebApplication1.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        public JsonResult GetAllEmployees()
        {
            Repository obj = new Repository();
            IEnumerable<Employee> Employee = null;
            Employee = obj.GetAllEmployees();
            return Json(Employee, JsonRequestBehavior.AllowGet);
        }
        public JsonResult SaveEmployee(Employee emp)
        {
            Repository obj = new Repository();
            bool output = obj.SaveEmployee(emp);
            return Json(new { success = output }, JsonRequestBehavior.AllowGet);
        }
        public JsonResult DeleteEmployee(int ID)
        {
            Repository obj = new Repository();
            bool output = obj.DeleteEmployee(ID);
            return Json(new { success = output }, JsonRequestBehavior.AllowGet);
        }
      }
}

Adding View

Now, right click on home controller index action method, add new view and name Index. Select Empty template and uncheck Use layout page and click on Add as shown below.

Addling index view

Now go to Views / Home folder, open Index.cshtml file and replace all code with below code. We need to download all the js and css file from internet.

Index.cshtml Code:
@{
    ViewBag.Title = "Angular CURD operation in ASP.NET MVC";
}

@* required angular and jquery js file *@
<script src="~/Scripts/jquery-3.3.1.js"></script>
<script src="~/Scripts/angular.js"></script>

@* custom javascript file where we write angular code *@
<script src="~/Scripts/myJavaScripts.js"></script>

@* for bootstrap modal and css to work *@
<script src="~/Scripts/bootstrap.js"></script>
<link href="~/Content/bootstrap.css" rel="stylesheet" />

@*optional for font icon*@
<link href="~/Content/font-awesome.css" rel="stylesheet" />


<div ng-app="myApp">
    <div ng-controller="myCtrl" ng-init="GetAllEmployees()">
        <table>
            <tr style="float:right;">
                <td>
                    <button type="button" class ="btn btn-success" ng-click="AddNewClick()" data-target="#addEmployee" data-toggle="modal">
                        <i class="fa fa-plus"> </i> Add New
                    </button>
                </td>
            </tr>
            <tr>
                <td>
                    <table class ="table table-hover table-dark table-condensed table-bordered">
                        <thead>
                            <tr>
                                <th scope="col">ID</th>
                                <th scope="col">Name</th>
                                <th scope="col">Gender</th>
                                <th scope="col">Salary</th>
                                <th scope="col"> Edit / Delete </th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr ng-repeat="employee in employees">
                                <td>{{employee.ID}}</td>
                                <td>{{employee.Name}}</td>
                                <td>{{employee.Gender}}</td>
                                <td>{{employee.Salary}}</td>
                                <td>
                                    <button class="btn btn-default" ng-click="EditEmployee(employee)" data-target="#addEmployee" data-toggle="modal">
                                        <i class="fa fa-edit"></i>
                                    </button>
                                    <button class="btn btn-danger" ng-click="DeleteEmployee(employee)">
                                        <i class="fa fa-trash"></i>
                                    </button>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </td>
            </tr>
        </table>

        <div id="addEmployee" class ="modal fade" role="dialog">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h4 class="modal-title" id="idTitle">Add Employee Detail</h4>
                        <button type="button" class="close" data-dismiss="modal">×</button>
                    </div>
                    <div class="modal-body">
                        <input type="hidden" ng-model="ID" />
                        <div class="form-group">
                            <label>Name:</label>
                            <input type="text" class="form-control" id="addName" ng-model="Name" maxlength="100">
                        </div>
                        <div class="form-group">
                            <label>Gender:</label>
                            <select class="form-control" id="addGender" ng-model="Gender">
                                <option value="">--Select--</option>
                                <option value="Male">Male</option>
                                <option value="Female">Female</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Salary:</label>
                            <input type="text" class="form-control" id="addSalary" ng-model="Salary" maxlength="10">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="submit" class ="btn btn-success" ng-click="SaveEmployee()"><i class ="fa fa-save"></ i> Save</button>
                        <button type="button" class ="btn btn-default" data-dismiss="modal"><i class ="fa fa-close"></ i> Cancel</button>
                    </div>
                </div>
            </div>
        </div>

    </div>
</div>

Writing AngularJS Code in Custom JavaScript File

Now, we need to write custom javascript file myJavaScripts.js and save in Scripts folder. Now drag and drop Angular.js and jQuery.js files at the top of custom javascript file for the reference as shown below.

/// <reference path="angular.js" />
/// <reference path="jquery-3.3.1.js" />
var app = angular.module("myApp", []);
app.controller("myCtrl", function ($scope, $http) {

    $scope.GetAllEmployees = function () {
        $http({
            method: "GET",
            url: "../Home/GetAllEmployees"
        }).then(function (response) {

            $scope.employees = response.data;
        }, function () {
            alert("Error occured!!!");
        })
    };

    $scope.SaveEmployee = function () {

        if ($('#addName').val() == "") {
            alert('Enter Name');
            return false;
        }
        if ($('#addGender' ).val() == "") {
            alert('Select Gender');
            return false;
        }
        var EmployeeModel = {
            ID: $scope.ID,
            Name: $scope.Name,
            Gender: $scope.Gender,
            Salary: $scope.Salary,
        };


        $http({
            method: "Post",
            datatype: "json",
            data: JSON.stringify(EmployeeModel),
            url: "../Home/SaveEmployee"
        }).then(function (response) {
            if (response.data.success == true) {
              alert('Saved successfully!!!!');
              $scope.ID = "";
              $scope.Name = "";
              $scope.Gender = "";
              $scope.Salary = "";
              $("#addEmployee").modal("toggle");
              $scope.GetAllEmployees();
            }
            else {
                alert( 'Save failed!!!');
            }

        }, function () {
            alert("Error occured!!!");
        })
    }

    $scope.EditEmployee = function (emp) {
        $scope.ID = emp.ID;
        $scope.Name = emp.Name;
        $scope.Gender = emp.Gender;
        $scope.Salary = emp.Salary;
        $('#idTitle').text('Update Employee Detail');
    }

    $scope.AddNewClick= function()
    {
        $scope.ID = "";
        $scope.Name = "";
        $scope.Gender = "";
        $scope.Salary = "";
        $('#idTitle').text('Add Employee Detail');
    }

    $scope.DeleteEmployee = function (emp) {

        if (confirm("Are you sure you want to delete this Employee?")) {
            $http({
                method: "Post",
                datatype: "json",
                data: { ID: emp.ID },
                url: "../Home/DeleteEmployee"
            }).then(function (response) {

                if (response.data.success == true) {
                    alert( 'Deleted successfully!!!');
                    $scope.GetAllEmployees();
                }
                else {
                    alert( 'Save failed!!!');
                }

            }, function () {
                alert( "Error occured!!!" );
            })
        }
    };
});

Output can be seen below as there are no records initially.

Angular CURD operation in ASP.NET MVC.png

Now click on Add New button to add new record in modal popup.

Adding record using angularjs in mvc

Now click on Save button to save record and reload the employee records.

Bind record using angularjs

Now you can edit and delete record as well.





blog comments powered by Disqus