AngularJS CRUD Operation : Select Insert Edit Update and Delete using AngularJS in ASP.Net MVC
Today in this article, I will explain AngularJS CRUD Operation Select Insert Edit Update and Delete using AngularJS in ASP.Net MVC application. In this example, I have used store procedure for database operation and Angularjs with MVC.
AngularJS is a framework for creating dynamic web application. Using AngularJS we can create single page dynamic web application. AngularJS provides feature for data binding in HTML page. AngularJS code is unit testable. AngularJS provides developers options to write client side application in a MVC way.
Step 1 : Create New Project
Go to File > New > Project > Web > Asp.net MVC web project > Enter Application Name > Select your project location > click to add button > It will show new dialog window for select template > here we will select empty project > then click to ok
Step 2 : Now create database
Step 3 : Create store procedure for Crude operation (Insert,update,delete, edit and delete)
Step 2 : Now create database
Step 3 : Create store procedure for Crude operation (Insert,update,delete, edit and delete)
(1) Create store procedure for select record
CREATE PROCEDURE [dbo].[sp_getEmployee]
@EmpID int=null
AS
if(@EmpID>0)
BEGIN
select * from tbEmployee where EmpID=@EmpID
END
else
begin
select * from tbEmployee
end
(2) Create store procedure for Add / Update Record
CREATE PROCEDURE [dbo].[SP_InsertEmployee]
@EmpID int,
@Name nvarchar(20),
@City nvarchar(20),
@Phone nvarchar(20)
AS
if(@EmpID>0)
begin
update tbEmployee set Name=@Name,City=@City,Phone=@Phone where EmpID=@EmpID
end
else
begin
insert into tbEmployee(Name,City,Phone)values(@Name,@City,@Phone);
END
(3) Create store procedure for Delete Record
CREATE PROCEDURE [dbo].[DeleteEmployee]
@EmpID int
as
BEGIN
Delete from tbEmployee where EmpID=@EmpID
END
CREATE PROCEDURE [dbo].[sp_getEmployee]
@EmpID int=null
AS
if(@EmpID>0)
BEGIN
select * from tbEmployee where EmpID=@EmpID
END
else
begin
select * from tbEmployee
end
(2) Create store procedure for Add / Update Record
CREATE PROCEDURE [dbo].[SP_InsertEmployee]
@EmpID int,
@Name nvarchar(20),
@City nvarchar(20),
@Phone nvarchar(20)
AS
if(@EmpID>0)
begin
update tbEmployee set Name=@Name,City=@City,Phone=@Phone where EmpID=@EmpID
end
else
begin
insert into tbEmployee(Name,City,Phone)values(@Name,@City,@Phone);
END
(3) Create store procedure for Delete Record
CREATE PROCEDURE [dbo].[DeleteEmployee]
@EmpID int
as
BEGIN
Delete from tbEmployee where EmpID=@EmpID
END
Step 4: Create a model class "Home.cs"
public class Home
{
public int EmpID { get; set; }
public string Name { get; set; }
public string Phone { get; set; }
public string City { get; set; }
}
{
public int EmpID { get; set; }
public string Name { get; set; }
public string Phone { get; set; }
public string City { get; set; }
}
Step 5: Create a controller "Employee "
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using AngularJs_Practicle.Models;
namespace AngularJs_Practicle.Controllers
{
public class EmployeeController : Controller
{
//
// GET: /Employee/
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);
public ActionResult Index()
{
return View();
}
public JsonResult GetEmployee()
{
return Json(Select_data(0).ToList(), JsonRequestBehavior.AllowGet);
}
public JsonResult getEmployeeById(string EmpID)
{
int EmpIDs = Convert.ToInt32(EmpID);
return Json(Select_data(EmpIDs).ToList(), JsonRequestBehavior.AllowGet);
}
public List<Home> Select_data(int id = 0)
{
List<Home> D = new List<Home>();
try
{
con.Open();
SqlCommand cmd = new SqlCommand("sp_getEmployee", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@EmpID", SqlDbType.Int);
cmd.Parameters["@EmpID"].Value = id;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Home da = new Home();
da.EmpID = Convert.ToInt32(dr["EmpID"].ToString());
da.Name = dr["Name"].ToString();
da.Phone = dr["Phone"].ToString();
da.City = dr["City"].ToString();
D.Add(da);
}
dr.Dispose();
con.Close();
}
catch (Exception)
{
}
return D;
}
public string AddEmployee(Home h)
{
con.Open();
SqlCommand cmd = new SqlCommand("SP_InsertEmployee", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@EmpID", SqlDbType.Int);
cmd.Parameters.Add("@Name", SqlDbType.VarChar);
cmd.Parameters.Add("@Phone", SqlDbType.VarChar);
cmd.Parameters.Add("@City", SqlDbType.VarChar);
cmd.Parameters["@EmpID"].Value = h.EmpID > 0 ? h.EmpID : 0;
cmd.Parameters["@Name"].Value = h.Name;
cmd.Parameters["@Phone"].Value = h.Phone;
cmd.Parameters["@City"].Value = h.City;
cmd.ExecuteNonQuery();
con.Close();
cmd.Dispose();
return "Record Submited Succesfully";
}
public string DeleteEmployee(string EmpID)
{
con.Open();
SqlCommand cmd = new SqlCommand("DeleteEmployee", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@EmpID", SqlDbType.Int);
cmd.Parameters["@EmpID"].Value = EmpID;
cmd.ExecuteNonQuery();
con.Close();
cmd.Dispose();
return "Delete Record succesfully";
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using AngularJs_Practicle.Models;
namespace AngularJs_Practicle.Controllers
{
public class EmployeeController : Controller
{
//
// GET: /Employee/
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);
public ActionResult Index()
{
return View();
}
public JsonResult GetEmployee()
{
return Json(Select_data(0).ToList(), JsonRequestBehavior.AllowGet);
}
public JsonResult getEmployeeById(string EmpID)
{
int EmpIDs = Convert.ToInt32(EmpID);
return Json(Select_data(EmpIDs).ToList(), JsonRequestBehavior.AllowGet);
}
public List<Home> Select_data(int id = 0)
{
List<Home> D = new List<Home>();
try
{
con.Open();
SqlCommand cmd = new SqlCommand("sp_getEmployee", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@EmpID", SqlDbType.Int);
cmd.Parameters["@EmpID"].Value = id;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Home da = new Home();
da.EmpID = Convert.ToInt32(dr["EmpID"].ToString());
da.Name = dr["Name"].ToString();
da.Phone = dr["Phone"].ToString();
da.City = dr["City"].ToString();
D.Add(da);
}
dr.Dispose();
con.Close();
}
catch (Exception)
{
}
return D;
}
public string AddEmployee(Home h)
{
con.Open();
SqlCommand cmd = new SqlCommand("SP_InsertEmployee", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@EmpID", SqlDbType.Int);
cmd.Parameters.Add("@Name", SqlDbType.VarChar);
cmd.Parameters.Add("@Phone", SqlDbType.VarChar);
cmd.Parameters.Add("@City", SqlDbType.VarChar);
cmd.Parameters["@EmpID"].Value = h.EmpID > 0 ? h.EmpID : 0;
cmd.Parameters["@Name"].Value = h.Name;
cmd.Parameters["@Phone"].Value = h.Phone;
cmd.Parameters["@City"].Value = h.City;
cmd.ExecuteNonQuery();
con.Close();
cmd.Dispose();
return "Record Submited Succesfully";
}
public string DeleteEmployee(string EmpID)
{
con.Open();
SqlCommand cmd = new SqlCommand("DeleteEmployee", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@EmpID", SqlDbType.Int);
cmd.Parameters["@EmpID"].Value = EmpID;
cmd.ExecuteNonQuery();
con.Close();
cmd.Dispose();
return "Delete Record succesfully";
}
}
}
Step 6: Add AngularJS library and AngularJS Controller.js file, Module.js file and Service.js file :
<script src="~/Scripts/angular.min.js"></script>
<script src="~/Angular/Module.js"></script>
<script src="~/Angular/Service.js"></script>
<script src="~/Angular/Controller.js"></script>
Step 7 : Add code to Module.js file
var myapp;
(function () {
myapp = angular.module('MyApps', []);
})();
(function () {
myapp = angular.module('MyApps', []);
})();
Step 8 : Add code to Service.js file
myapp.service('myService', function ($http) {
this.getEmployees = function () {
debugger;
return $http.get('/Employee/GetEmployee');
}
this.AddEmployee = function (employee) {
debugger;
var Resp = $http({
method: "post",
url: "/Employee/AddEmployee",
data: JSON.stringify(employee),
dataType: "json"
});
return Resp;
}
this.getEmployeeById = function (EmpID) {
debugger;
var Resp = $http({
method: "post",
url: "/Employee/getEmployeeById",
params: {
EmpId: JSON.stringify(EmpID)
},
dataType: "json"
});
return Resp;
}
this.DeleteEmployee = function (employee) {
var response = $http({
method: "post",
url: "/Employee/DeleteEmployee",
params: {
EmpID: JSON.stringify(employee.EmpID)
}
});
return response;
}
});
Step 8 : Add code to Controller.js file
myapp.controller('EmployeeController', function ($scope, myService) {
GetEmployee();
//To Get All Records
function GetEmployee() {
debugger;
var getData = myService.getEmployees();
debugger;
getData.then(function (emp) {
$scope.employees = emp.data;
}, function () {
alert('Error while getting records');
});
}
$scope.AddUpdateEmployee = function () {
debugger;
var Employee = {
EmpID:$scope.EmpID,
Name: $scope.Name,
Phone: $scope.Phone,
City: $scope.City
};
var getAction = $scope.Action;
if (getAction == "Update") {
Employee.Id = $scope.EmpID;
var getData = myService.AddEmployee(Employee);
getData.then(function (msg) {
GetEmployee();
alert(msg.data);
$scope.divEmployee = false;
}, function () {
alert('Error in updating record');
});
} else {
var getData = myService.AddEmployee(Employee);
getData.then(function (msg) {
GetEmployee();
alert(msg.data);
$scope.divEmployee = false;
}, function () {
alert('Error in adding record');
});
}
}
$scope.editEmployee = function (employee) {
debugger;
var getData = myService.getEmployeeById(employee.EmpID);
getData.then(function (emp) {
$scope.employee = emp.data;
$scope.EmpID = employee.EmpID;
$scope.Name = employee.Name;
$scope.Phone = employee.Phone;
$scope.City = employee.City;
$scope.Action = "Update";
$scope.divEmployee = true;
},
function () {
alert('Error in getting records');
});
}
$scope.deleteEmployee = function (employee) {
var getData = myService.DeleteEmployee(employee);
getData.then(function (msg) {
GetEmployee();
alert('Employee Deleted');
}, function () {
alert('Error in Deleting Record');
});
}
$scope.AddEmployeeDiv = function () {
ClearFields();
$scope.Action = "ADD";
$scope.divEmployee = true;
}
function ClearFields() {
$scope.empId = "";
$scope.Name = "";
$scope.Email = "";
$scope.phone = "";
}
});
GetEmployee();
//To Get All Records
function GetEmployee() {
debugger;
var getData = myService.getEmployees();
debugger;
getData.then(function (emp) {
$scope.employees = emp.data;
}, function () {
alert('Error while getting records');
});
}
$scope.AddUpdateEmployee = function () {
debugger;
var Employee = {
EmpID:$scope.EmpID,
Name: $scope.Name,
Phone: $scope.Phone,
City: $scope.City
};
var getAction = $scope.Action;
if (getAction == "Update") {
Employee.Id = $scope.EmpID;
var getData = myService.AddEmployee(Employee);
getData.then(function (msg) {
GetEmployee();
alert(msg.data);
$scope.divEmployee = false;
}, function () {
alert('Error in updating record');
});
} else {
var getData = myService.AddEmployee(Employee);
getData.then(function (msg) {
GetEmployee();
alert(msg.data);
$scope.divEmployee = false;
}, function () {
alert('Error in adding record');
});
}
}
$scope.editEmployee = function (employee) {
debugger;
var getData = myService.getEmployeeById(employee.EmpID);
getData.then(function (emp) {
$scope.employee = emp.data;
$scope.EmpID = employee.EmpID;
$scope.Name = employee.Name;
$scope.Phone = employee.Phone;
$scope.City = employee.City;
$scope.Action = "Update";
$scope.divEmployee = true;
},
function () {
alert('Error in getting records');
});
}
$scope.deleteEmployee = function (employee) {
var getData = myService.DeleteEmployee(employee);
getData.then(function (msg) {
GetEmployee();
alert('Employee Deleted');
}, function () {
alert('Error in Deleting Record');
});
}
$scope.AddEmployeeDiv = function () {
ClearFields();
$scope.Action = "ADD";
$scope.divEmployee = true;
}
function ClearFields() {
$scope.empId = "";
$scope.Name = "";
$scope.Email = "";
$scope.phone = "";
}
});
Step 9 : add view index.cshtml
<script src="~/Scripts/angular.min.js"></script>
<script src="~/Angular/Module.js"></script>
<script src="~/Angular/Service.js"></script>
<script src="~/Angular/Controller.js"></script>
<div ng-app="MyApps" ng-controller="EmployeeController">
<h1>Employee Details</h1>
<input type="button" class="btnAdd" value=" Add Employee" ng-click="AddEmployeeDiv()" />
<div ng-show="divEmployee">
<p class="divHead"><b>{{Action}} Employee </b></p>
<table>
<tr>
<td style="display:none;"><b>EmpID</b></td>
<td style="display:none;">
<input type="text" disabled="disabled" ng-model="EmpID" />
</td>
</tr>
<tr>
<td ><b>Name</b></td>
<td>
<input type="text" ng-model="Name" />
</td>
</tr>
<tr>
<td><b>Phone</b></td>
<td>
<input type="text" ng-model="Phone" />
</td>
</tr>
<tr>
<td><b>City</b></td>
<td>
<input type="text" ng-model="City" />
</td>
</tr>
<tr>
<td colspan="2">
<input type="button" class="btnAdd" value="Save" ng-click="AddUpdateEmployee()" />
</td>
</tr>
</table>
</div>
<div class="divList">
<p class="divHead"> <b>Employee List </b></p>
<table cellpadding="12" class="table table-bordered table-hover">
<tr>
<td style="display:none;"><b>ID</b></td>
<td><b>Name</b></td>
<td><b>Email</b></td>
<td><b>Age</b></td>
<td><b>Actions</b></td>
</tr>
<tr ng-repeat="employee in employees">
<td style="display:none;">
{{employee.EmpID}}
</td>
<td>
{{employee.Name}}
</td>
<td>
{{employee.Phone}}
</td>
<td>
{{employee.City}}
</td>
<td>
<input type="button" ng-click="editEmployee(employee)" class="btnAdd" value="Edit" />
<input type="button" ng-click="deleteEmployee(employee)" class="btnRed" value="Delete">
</td>
</tr>
</table>
</div>
</div>
<script src="~/Angular/Module.js"></script>
<script src="~/Angular/Service.js"></script>
<script src="~/Angular/Controller.js"></script>
<div ng-app="MyApps" ng-controller="EmployeeController">
<h1>Employee Details</h1>
<input type="button" class="btnAdd" value=" Add Employee" ng-click="AddEmployeeDiv()" />
<div ng-show="divEmployee">
<p class="divHead"><b>{{Action}} Employee </b></p>
<table>
<tr>
<td style="display:none;"><b>EmpID</b></td>
<td style="display:none;">
<input type="text" disabled="disabled" ng-model="EmpID" />
</td>
</tr>
<tr>
<td ><b>Name</b></td>
<td>
<input type="text" ng-model="Name" />
</td>
</tr>
<tr>
<td><b>Phone</b></td>
<td>
<input type="text" ng-model="Phone" />
</td>
</tr>
<tr>
<td><b>City</b></td>
<td>
<input type="text" ng-model="City" />
</td>
</tr>
<tr>
<td colspan="2">
<input type="button" class="btnAdd" value="Save" ng-click="AddUpdateEmployee()" />
</td>
</tr>
</table>
</div>
<div class="divList">
<p class="divHead"> <b>Employee List </b></p>
<table cellpadding="12" class="table table-bordered table-hover">
<tr>
<td style="display:none;"><b>ID</b></td>
<td><b>Name</b></td>
<td><b>Email</b></td>
<td><b>Age</b></td>
<td><b>Actions</b></td>
</tr>
<tr ng-repeat="employee in employees">
<td style="display:none;">
{{employee.EmpID}}
</td>
<td>
{{employee.Name}}
</td>
<td>
{{employee.Phone}}
</td>
<td>
{{employee.City}}
</td>
<td>
<input type="button" ng-click="editEmployee(employee)" class="btnAdd" value="Edit" />
<input type="button" ng-click="deleteEmployee(employee)" class="btnRed" value="Delete">
</td>
</tr>
</table>
</div>
</div>
Step 10 : Run Application and see output
Hi, friend if you need to code or need help re-guarding this Angularjs article than feel free to contact or attached your email in comment section.
See Other Tutorial :
* AngularJS With ASP.NET MVC
* Convert Rows to columns using 'Pivot' in SQL Server
* Mvc Registration page With user exist using Ajax method
* MVC 4 How to Perform Insert Update Delete Edit Select Operation
* MVC4 Edit,update,Delete,cancel inside gridview using sql database
* MVC 4 Gridview To Display Data Using SQL Server Database With Simple code
* Login page in asp.net Mvc4 Web application
* Mvc4 How to bind Dropdown List using Sql Database
* Gridview find control in asp.net
Sign up here with your email
ConversionConversion EmoticonEmoticon