AngularJS CRUD Operation Using ASP.NET MVC
Introduction:
Today in this tutorial we have learn 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 crude 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)
(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
@EmpID int
as
BEGINDelete 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; }
}
Step 5: Create a controller “Employee “
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 Select_data(int id = 0)
{
List D = new List();
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‘, []);
})();
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 9 : 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 = “”;
}
});
Step 10 : 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>
Now run run your web project and see output
SEE MORE
- Auto Refresh Partial View in ASP.NET MVC
- What is ASP.NET Core
- Difference between TempData keep() And Peek() in Asp.Net MVC
- Difference between viewbag,viewdata and tempdata in asp.net mvc
- ASP.NET MVC With AngularJS
- Retrieving Data Using Form Collection and Inserting Into ASP.Net MVC
- MVC CRUD Operations Using Entity Framework
- Search Functionality in ASP.NET MVC
- How to create a User Registration page using asp.net mvc
- Store Multiple Checkbox state from cookie using Jquery
- Cascading Dropdownlist using Ajax in Asp.Net Mvc with city state country
- Insert, Update, Delete In GridView Using ASP.Net C#
- Binding Dropdownlist With Database In Asp.Net MVC
- Search and Filter data in Gridview using Asp.net MVC
- Select Insert, Update And Delete With ASP.NET MVC
- Display Data in GridView Using Asp.net MVC
- Validation in ASP.NET MVC Razor view
- CRUD Operation Using 3-Tier Architecture In ASP.NET
- How to get Connection String from Web.Config in Asp.Net C#
- Login page using 3-Tier Architecture in ASP.Net
- Asp.Net Image Upload in 3-Tier Architecture and store in sql database