Codechef4u is a community for computer professionals,by computer professionals,just like you; who loves sharing and helping each others,Join them
Share your post

CRUD Operation in ASP.NET MVC and AngularJS

Insert,Update,Delete in AngularJS and ASP.NET MVC 

In this post I will create sample Asp.net MVC 4 application using AngularJS and perform

CRUD (Create, Read, Update and Delete) operations using SPA (Single Page Application).

First create Asp.net MVC 4 application named “AngularMVC” and then simply follow below steps.

1.  Now create a new Employee class in model folder with name as Employee.cs and add below listed properties.

   public class Employee
     {
 
        [Key]
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public string Address { get; set; }
     }


2. Now create entity EmployeeContext.cs class in model folder.

  namespace AngularMVC.Models
  {
    public class EmployeeContext : DbContext
    {
        public EmployeeContext() : base("DefaultConnection")
        {
        }
 
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            Database.SetInitializer<EmployeeContext>(null);
        }
        public DbSet<Employee> EmployeeData { get; set; }
    }
  }


3. Now let's add following code in HomeController to Retrieve, Insert, Update and delete Employee records.

       // GET: All Employees
        public JsonResult GetAllEmployees()
        {
            using (EmployeeContext contextObj = new EmployeeContext()))
            {
                var EmployeeList = contextObj.EmployeeData.ToList();
                return Json(EmployeeList, JsonRequestBehavior.AllowGet);
            }
        }
 
        // Insert/ADD new employee
        public JsonResult Save(Employee data)
        {
            using (EmployeeContext contextObj = new EmployeeContext())
            {
                var EmployeeList = contextObj.EmployeeData.Add(data);
                contextObj.SaveChanges();
            }
            return null;
 
        }
 
        // Update existing employee
        public JsonResult Update(int id,string name,string email,string address)
        {
            using (EmployeeContext contextObj = new EmployeeContext())
            {
                var employeeList = contextObj.EmployeeData.Where(x => x.Id ==  id).FirstOrDefault();
                employeeList.Name = name;
                employeeList.Email = email;
                employeeList.Address = address;
               
                contextObj.SaveChanges();
            }
            return null;
        }
 
        // Delete existing employee
        public JsonResult Delete(int id)
        {
            using (EmployeeContext contextObj = new EmployeeContext())
            {
                var employeeList = contextObj.EmployeeData.Where(x => x.Id == id).FirstOrDefault();
                contextObj.EmployeeData.Remove(employeeList);
                contextObj.SaveChanges();
            }
            return null;
        }
 

4. Change existing connection string or Add database connection in web.config.

<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=.\;Initial Catalog=SampleAngularMVCDb;Integrated Security=True;" providerName="System.Data.SqlClient" />
  </connectionStrings>

5. Go to Scripts and create a new folder as EmployeeScripts, under EmployeeScripts folder create 3 new js files as AngApp.js, EmpController.js & EmpService.js.

 

6. Now under shared folder there is view named _Layout.cshtm, add all these scripts files in that shared view.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>@ViewBag.Title - My ASP.NET MVC Application</title>
        <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
        <meta name="viewport" content="width=device-width" />
        @Styles.Render("~/Content/css")
        @Scripts.Render("~/bundles/modernizr")
        <script src="~/EmployeeScripts/js/angular.min.js"></script>
        <script src="~/EmployeeScripts/js/AngApp.js"></script>
        <script src="~/EmployeeScripts/js/EmpController.js"></script>
        <script src="~/EmployeeScripts/js/EmpService.js"></script>
    </head>
   <body>
….
</body>
</html>


7. Now let’s create view named Index.cshtml with AngularJS code under folder Home, then add ng-app,ng-controller,ng-model,ng-repeat,ng-click AnularJS directives in this view with required html code.

 @{
    ViewBag.Title = "Home Page";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<div ng-app="EmpApp" ng-controller="EmpCntrlr">
   
        <table border="1" cellpadding="10" align="center">
 
            <tr>
                <td colspan="4">
                    <form name="myForm" novalidate>
                        <table>
                            <tr>
                                <td>
                                    <input type="hidden" id="txtid" name="id" ng-model="employeeData.Id" />
                                </td>
                                <td>
                                    Name:
                                    <input type="text" id="txtEmpName" name="name" ng-model="employeeData.Name" />
                                </td>
                                <td>
                                    Email:
                                    <input type="email" id="txtEmpEmail" name="email" ng-model="employeeData.Email" />
                                    <span ng-show="myForm.email.$error.email">Invalid email address.</span>
                                </td>
                                <td>
                                    Address:
                                    <input type="text" id="txtEmpAddress" name="address" ng-model="employeeData.Address" />
                                </td>
                            </tr>
                            <tr>
                                <td colspan="3" style="text-align:right">
                                    <button ng-click="myForm.$valid && Save()">Save</button>
                                   
                                </td>
                            </tr>
                        </table>
                    </form>
          </td>
            </tr>
 
            <tr>
                <th>
                   
                </th>
                <th>
                    Name
                </th>
                <th>
                    Email
                </th>
                <th>
                    Address
                </th>
            </tr>
            <tr ng-repeat="emp in employees|orderBy :'Id'">
 
                <td>
                </td>
                <td>
                    <input type="text" id="txtName" ng-model="emp.Name" />
                </td>
                <td>
                    <input type="text" id="txtem" ng-model="emp.Email" />
                </td>
                <td>
                    <input type="text" id="txtadd" ng-model="emp.Address" />
                </td>
                <td>
                    <button ng-click="Delete(emp.Id)">Delete</button>
                </td>
                <td>
                    <button ng-click="Update(emp.Id,emp.Name,emp.Email,emp.Address)">Update</button>
                </td>
            </tr>
        </table>
</div>
 


8. Open AngApp.js and define angular module as below

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

9. Open EmpService.js and define functions for CRUD (insert, update, delete) operations on Employee.

app.service("EmployeeService", function ($http) {
 
    // Get Employee data
    this.getEmployee = function () {
        debugger;
        return $http.get("/Home/GetAllEmployees");
    };
    // Delete Employee by Id
    this.DeleteEmployee = function (EmpID) {
        var response = $http({
            method: "post",
            url: "Home/Delete",
            params: {
                id: EmpID
            }
        });
        return response;
    }
    // Update Employee
    this.UpdateEmployee = function (Id, Name, Email, Address) {
        var response = $http({
            method: "post",
            url: "Home/Update",
            params: {
                id: Id, name: JSON.stringify(Name), email: JSON.stringify(Email), address: JSON.stringify(Address)
            }
        });
        return response;
    }
});

 

10.  Open EmpController.js and all required functions(i.e clear(),setdefaultdata() etc) with CRUD operations.

app.controller("EmpCntrlr", function ($scope, EmployeeService) {
    GetAllEmployee();
    function GetAllEmployee() {
        debugger;
        var getAllEmployee = EmployeeService.getEmployee();
        getAllEmployee.then(function (empls) {
            $scope.employees = empls.data;
        }, function () {
            alert('Employee data not found');
        });
    }
 
    $scope.employeeData= {
 
        id: 0,
 
        Name: 'nagnath',
 
        Email: 'test@gmail.com',
 
        Address: 'ok'
 
    }
 
    $scope.Save = function () {
        $.ajax({
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify($scope.employeeData),
            url: '/Home/Save',
            success: function (data, status) {
                ClearFields();
                GetAllEmployee();
            },
            error: function (status) { }
        });
    }
 
     // Angular ajax function deletes employee data for selected employee
       $scope.Delete = function (EmpId) {
        debugger;
        var DelEmployee = EmployeeService.DeleteEmployee(EmpId);
        DelEmployee.then(function (empls) {
            ClearFields();
            GetAllEmployee();
        }, function () {
            alert('Employee data not found');
        });
       }
    // Angular ajax function Update employee data for selected employee
       $scope.Update = function (Id,Name,Email,Address) {
           debugger;
           var UpdateEmployeeData = EmployeeService.UpdateEmployee(Id, Name, Email, Address);
           UpdateEmployeeData.then(function (empls) {
               ClearFields();
               GetAllEmployee();
           }, function () {
               alert('Employee data not found');
           });
       }
 
    function ClearFields() {
        $scope.Name = "";
        $scope.Email = "";
        $scope.Address = "";
      
    }
 
});
 

Final Page Look 


CRUD with Angular.js and Asp.net,Sql Server

Insert,Update,Delete with Asp.net,AngularJS Ajax

In this post, I am going to explain in detail a sample example that will insert, update, delete, and display retrieved data using simple Asp.net,AngularJS Ajax and SQL Server.

I will explain example in detail with some following steps

Step 1(Database code MS SQL Server)

Create Sql server simple table names Employee with columns ID, Name, Email, and Address.

Employee Table

 

Create stored procedure to retrieve data; here I created stored procedure to retrieve data only to insert, update, and delete operation I am going to use parameterized inline query but I recommend using stored procedure or entity framework for it.

Stored procedure to retrieve data

CREATE PROCEDURE [dbo].[GetAllEmployees_SP]  
AS BEGIN
   SELECT [ID] ,
            [Name],
            [Email] as EmailID,
            [Address]
            FROM [dbo].[Employee] Where DeletedDate is null
END


Step 2(Angular JS View):

AngularJS View and Asp.net UI mix code

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <script src="Content/js/Employee.js"></script>
</head>
<body>
 
    <form id="form1" runat="server">
     <div ng-app="myApp" ng-controller="myEmpCntrl">
        <table border="1" cellpadding="10" align="center" class="table table-bordered table-striped">
            <tr>
                <td colspan="4">
                <table>
               <tr>
                <td>             
                </td>
                <td> Name:
                <input type="text" id="txtEmpName" ng-model="EmpName" />
                </td>
                <td>
                   Email:
                <input type="text" id="txtEmpEmail" ng-model="EmpEmail" />
                </td>
                <td>
                 Address:
                  <input type="text" id="txtEmpAddress" ng-model="EmpAddress" />
                </td>
              </tr>
               <tr>   
               <td colspan="3" style="text-align:right">  
                 <button ng-click="Save()">Save</button>              
                </td>
               </tr>
                </table>
             </td>
            </tr>
            <tr>
                <th>
                    Employee Id
                </th>
                <th>
                    Employee Name
                </th>
                <th>
                    Address
                </th>
                <th>
                    Email Id
                </th>
            </tr>
            <tr ng-repeat="emp in Employees|orderBy :'Name'">
                <td>
                    <input type="text" id="Text2" ng-model="emp.Id" />
                </td>
                <td>
                     <input type="text" id="Text1" ng-model="emp.Name" />
                </td>
                <td>
                    <input type="text" id="Text3" ng-model="emp.Address" />
                </td>
                <td>
                    <input type="text" id="Text4" ng-model="emp.EmailId" />
                </td>
                <td>
                    <button ng-click="Update(emp.Id,emp.Name,emp.Address,emp.EmailId)" >Update</button>
                    <button ng-click="Delete(emp.Id)" >Delete</button>
                </td>
            </tr>
            <tr>
                <td>
                    <button ng-click="fillList()" >Refresh</button>
                </td>
                </tr>
        </table>
 
            </div>
    </form>
</body>
</html>

Setp 3(AngularJS Controller And Model Code)

AngularJS Controller and Ajax Code (Employee.js fie)

// Angular app bootstrap start here
var app = angular.module("myApp", []);
//Angular controller
app.controller("myEmpCntrl", function ($scope, $http) {
//Angular  $scope and model data
    $scope.EmpID = 0;
    $scope.EmpName = "";
    $scope.EmpAddress = "";
    $scope.EmpEmail = "";
 
    // Angular Ajax function  used to Create or insert data in to employee table
    $scope.Save = function () {
        var httpreq = {
            method: 'POST',
            url: 'Default.aspx/Create',
            headers: {
                'Content-Type': 'application/json; charset=utf-8',
                'dataType': 'json'
            },
            data: { EmpName: $scope.EmpName, EmpAddress: $scope.EmpAddress, EmpEmail: $scope.EmpEmail }
        }
        $http(httpreq).success(function (response) {
            $scope.fillList();
            alert("Saved successfully.");
        })
    };
 
    // Angular ajax function deletes employee data for selected employee
    $scope.Delete = function (EmpId) {
        if (confirm("Are you sure want to delete?")) {
            var httpreq = {
                method: 'POST',
                url: 'Default.aspx/Delete',
                headers: {
                    'Content-Type': 'application/json; charset=utf-8',
                    'dataType': 'json'
                },
                data: { ID: EmpId }
            }
            $http(httpreq).success(function (response) {
                $scope.fillList();
                alert("Deleted successfully.");
            })
        }
    };
 
    // Angular ajax function update Employee data
    $scope.Update = function (EmpId, EmpName, EmpAddress, EmpEmailId) {
        if (confirm("Are you sure want to Update?")) {
            var httpreq = {
                method: 'POST',
                url: 'Default.aspx/Update',
                headers: {
 
                    'Content-Type': 'application/json; charset=utf-8',
                    'dataType': 'json'
                },
                data: { ID: EmpId, EmpName: EmpName, EmpAddress: EmpAddress, EmpEmail: EmpEmailId }
            }
            $http(httpreq).success(function (response) {
                $scope.fillList();
                alert("Updated successfully.");
            })
        }
    };
 
    //Angular ajax function retrieve and display employee data in table
    $scope.fillList = function () {
        var httpreq = {
            method: 'POST',
            url: 'Default.aspx/GetEmployeeList',
            headers: {
                'Content-Type': 'application/json; charset=utf-8',
                'dataType': 'json'
            },
            data: {}
        }
        $http(httpreq).success(function (data) {
 
            $scope.Employees = data.d;
 
        })
    };
    $scope.fillList();
});

 

Step 4(Asp.net Server side call to database)

Asp.net Server side Code

 

   
//Employee class
public class Employee  {
public int Id { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
        public string EmailId { get; set; }
  }

 

        //Web method is used to insert employee data into Employee table
        //using sql parameterized query
        [System.Web.Services.WebMethod()]
        public static void Create(string EmpName, string EmpEmail, string EmpAddress)
        {
            var constring = GetConnectionString();
            using (SqlConnection con = new SqlConnection(constring))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.Connection = con;
                    cmd.CommandText = "INSERT INTO Employee (EmployeeName,Email,Address) values (@EmployeeName,@Email,@Address);";
                    cmd.Parameters.AddWithValue("@EmployeeName", EmpName);
                    cmd.Parameters.AddWithValue("@Email", EmpEmail);
                    cmd.Parameters.AddWithValue("@Address", EmpAddress);
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
            }
        }
 
        //Web method is used to delete employee data from Employee table
        //using sql parameterized query
        [System.Web.Services.WebMethod()]
        public static void Delete(int ID)
        {
            var constring = GetConnectionString();
            using (SqlConnection con = new SqlConnection(constring))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.Connection = con;
                    cmd.CommandText = "UPDATE Employee SET DeletedDate=Getdate() WHERE ID=@ID;";
                    cmd.Parameters.AddWithValue("@ID", ID);
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
 
                }
            }
        }
 
        //Web method is used to Update employee data into Employee table
        //using sql parameterized query
        [System.Web.Services.WebMethod()]
        public static void Update(int ID,string EmpName,string EmpAddress,string EmpEmail)
        {
            var constring = GetConnectionString();
            using (SqlConnection con = new SqlConnection(constring))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.Connection = con;
                    cmd.CommandText = "UPDATE Employee SET EmployeeName=@EmployeeName,Email=@Email,Address=@Address WHERE ID=@ID;";
                    cmd.Parameters.AddWithValue("@ID", ID);
                    cmd.Parameters.AddWithValue("@EmployeeName", EmpName);
                    cmd.Parameters.AddWithValue("@Email", EmpEmail);
                    cmd.Parameters.AddWithValue("@Address", EmpAddress);
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
            }
        }
 
        //Web method retrieves data from sql server table
        [System.Web.Services.WebMethod()]
        public static List<Employee> GetEmployeeList()
        {
            var constring = GetConnectionString();
            List<Employee> Employees = new List<Employee>();
            DataSet ds = new DataSet();
            using (SqlConnection con = new SqlConnection(constring))
            {
                using (SqlCommand cmd = new SqlCommand("GetAllEmployees_SP", con))
                {
                   cmd.CommandType = CommandType.StoredProcedure;
                    using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                    {
                        da.Fill(ds);
                    }
                }
            }
 
            if (ds != null && ds.Tables.Count > 0)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                    Employees.Add(new Employee()
                    {
                        Id = int.Parse(dr["ID"].ToString()),
                        Name = dr["Name"].ToString(),
                        Address = dr["Address"].ToString(),
                        EmailId = dr["EmailID"].ToString()
                    });
            }
            return Employees;
        }
 
        //connection string
        public static string GetConnectionString()
        {
            string constring = ConfigurationManager.ConnectionStrings["C4Example"].ConnectionString;
            return constring;
 
        }

 

CS1026: ) expected (Asp.net button with ajax method call)

Facing following error with asp.net button, I used JavaScript Ajax method to cancel Approval.
Compiler Error Message: CS1026: ) expected

Source Code:

 

Line 99:  CommandName="Cancel"  Text="Cancel"  visible='<%# ShowCancelButton(Convert.ToString(Eval("Requester.FirstName"))) %>'/>--%>

Line 100:

Line 101: <asp:Button ID="CancelButton" runat="server" CssClass="wt-button" CausesValidation="False" OnClick=" CancelRequest(); return false;"

Line 102: CommandName="Cancel"  Text="Cancel" />

Line 103:

 

FIX:

With server side asp: Button  compiler will throw this error, use server side HTML button instead.

Source Code should be:

  <input type="button" ID="CancelButton" runat="server" Css="cs-button" CausesValidation="False" OnClick="
CancelRequest(); return false;" CommandName="Cancel"  Text="Cancel"  visible="True"  />