CRUD Operation In ASP.NET MVC Using AJAX And Bootstrap
작성자
관리자
작성일
2016-08-20
조회
8486
분류
ASP.NET
CRUDAjax.zip
Creating First Application In ASP.NET MVC
Pass Parameter Or Query String In Action Method In ASP.NET MVC
Passing Data from Controller To View In ASP.NET MVC
Strongly Typed View Vs Dynamically Typed View In ASP.NET MVC
Working With Built-In HTML Helper Classes In ASP.NET MVC
Inline and Custom HTML Helpers In ASP.NET MVC
What is AJAX and Bootstrap?
AJAX (Asynchronous JavaScript and XML) in the Web Application is used to update parts of the existing page and to retrieve the data from the Server asynchronously. AJAX improves the performance of the Web Application and makes the Application more interactive.
Bootstrap is one of the most popular HTML, CSS and JS frameworks for developing responsive, mobile first projects on the Web.
Let’s Begin
Create a new ASP.NET Web Application.
[이미지] http://csharpcorner.mindcrackerinc.netdna-cdn.com/article/crud-operation-in-asp-net-mvc-using-ajax-and-bootstrap/Images/image1.jpg
Select Empty ASP.NET MVC template and click OK.
[이미지] http://csharpcorner.mindcrackerinc.netdna-cdn.com/article/crud-operation-in-asp-net-mvc-using-ajax-and-bootstrap/Images/image2.jpg
Now, right-click on the project and click Manage NuGet Packages.
[이미지] http://csharpcorner.mindcrackerinc.netdna-cdn.com/article/crud-operation-in-asp-net-mvc-using-ajax-and-bootstrap/Images/image3.jpg
Search for Bootstrap and then click Install button.
[이미지] http://csharpcorner.mindcrackerinc.netdna-cdn.com/article/crud-operation-in-asp-net-mvc-using-ajax-and-bootstrap/Images/image4.jpg
After installing the package, you will see the Content and Scripts folder being added in your Solution Explorer.
[이미지] http://csharpcorner.mindcrackerinc.netdna-cdn.com/article/crud-operation-in-asp-net-mvc-using-ajax-and-bootstrap/Images/image5.jpg
Now, create a database and add a table (named Employee). The following is the schema for creating a table Employee:
[이미지] http://csharpcorner.mindcrackerinc.netdna-cdn.com/article/crud-operation-in-asp-net-mvc-using-ajax-and-bootstrap/Images/image6.jpg
After the table creation, create the stored procedures for Select, Insert, Update and Delete operations.
--Select Employees
Create Procedure SelectEmployee
as
Begin
Select * from Employee;
End
--Insert and Update Employee
Create Procedure InsertUpdateEmployee
(
@Id integer,
@Name nvarchar(50),
@Age integer,
@State nvarchar(50),
@Country nvarchar(50),
@Action varchar(10)
)
As
Begin
if @Action='Insert'
Begin
Insert into Employee(Name,Age,[State],Country) values(@Name,@Age,@State,@Country);
End
if @Action='Update'
Begin
Update Employee set Name=@Name,Age=@Age,[State]=@State,Country=@Country where EmployeeID=@Id;
End
End
--Delete Employee
Create Procedure DeleteEmployee
(
@Id integer
)
as
Begin
Delete Employee where EmployeeID=@Id;
End
Right click on Modal Folder and add Employee.cs class.
Employee.cs Code
public class Employee
{
public int EmployeeID { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string State { get; set; }
public string Country { get; set; }
}
Now, add another class in Modal Folder named as EmployeeDB.cs for the database related operations. In this example, I am going to use ADO.NET to access the data from the database.
public class EmployeeDB
{
//declare connection string
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
//Return list of all Employees
public List ListAll()
{
List lst = new List();
using(SqlConnection con=new SqlConnection(cs))
{
con.Open();
SqlCommand com = new SqlCommand("SelectEmployee",con);
com.CommandType = CommandType.StoredProcedure;
SqlDataReader rdr = com.ExecuteReader();
while(rdr.Read())
{
lst.Add(new Employee {
EmployeeID=Convert.ToInt32(rdr["EmployeeId"]),
Name=rdr["Name"].ToString(),
Age = Convert.ToInt32(rdr["Age"]),
State = rdr["State"].ToString(),
Country = rdr["Country"].ToString(),
});
}
return lst;
}
}
//Method for Adding an Employee
public int Add(Employee emp)
{
int i;
using(SqlConnection con=new SqlConnection(cs))
{
con.Open();
SqlCommand com = new SqlCommand("InsertUpdateEmployee", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("@Id",emp.EmployeeID);
com.Parameters.AddWithValue("@Name", emp.Name);
com.Parameters.AddWithValue("@Age", emp.Age);
com.Parameters.AddWithValue("@State", emp.State);
com.Parameters.AddWithValue("@Country", emp.Country);
com.Parameters.AddWithValue("@Action", "Insert");
i = com.ExecuteNonQuery();
}
return i;
}
//Method for Updating Employee record
public int Update(Employee emp)
{
int i;
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand com = new SqlCommand("InsertUpdateEmployee", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("@Id", emp.EmployeeID);
com.Parameters.AddWithValue("@Name", emp.Name);
com.Parameters.AddWithValue("@Age", emp.Age);
com.Parameters.AddWithValue("@State", emp.State);
com.Parameters.AddWithValue("@Country", emp.Country);
com.Parameters.AddWithValue("@Action", "Update");
i = com.ExecuteNonQuery();
}
return i;
}
//Method for Deleting an Employee
public int Delete(int ID)
{
int i;
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand com = new SqlCommand("DeleteEmployee", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("@Id", ID);
i = com.ExecuteNonQuery();
}
return i;
}
}
Right click on Controllers folder, add an Empty Controller and name it as HomeController.
[이미지] http://csharpcorner.mindcrackerinc.netdna-cdn.com/article/crud-operation-in-asp-net-mvc-using-ajax-and-bootstrap/Images/image7.jpg
Now, open HomeController and add the following action methods:
public class HomeController : Controller
{
EmployeeDB empDB = new EmployeeDB();
// GET: Home
public ActionResult Index()
{
return View();
}
public JsonResult List()
{
return Json(empDB.ListAll(),JsonRequestBehavior.AllowGet);
}
public JsonResult Add(Employee emp)
{
return Json(empDB.Add(emp), JsonRequestBehavior.AllowGet);
}
public JsonResult GetbyID(int ID)
{
var Employee = empDB.ListAll().Find(x => x.EmployeeID.Equals(ID));
return Json(Employee, JsonRequestBehavior.AllowGet);
}
public JsonResult Update(Employee emp)
{
return Json(empDB.Update(emp), JsonRequestBehavior.AllowGet);
}
public JsonResult Delete(int ID)
{
return Json(empDB.Delete(ID), JsonRequestBehavior.AllowGet);
}
}
Right click on the Index action method of HomeController and click on Add View. As we are going to use Bootstrap and AJAX, we have to add their relative Scripts and CSS references in the head section of the view. I have also added employee.js, which will contain all AJAX code, that are required for CRUD operation.
Add the code, given below, in Index.cshtml view:
Employees Record
ID
Name
Age
State
Country
Action
Add Employee
In the code, given above, we have added a button for adding New Employee. On clicking, It will open the modal dialog box of the bootstrap, which contains several fields of the employees for saving. We have also added a table, which will be populated with the use of AJAX.
Employee.js Code
//Load Data in Table when documents is ready
$(document).ready(function () {
loadData();
});
//Load Data function
function loadData() {
$.ajax({
url: "/Home/List",
type: "GET",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
var html = '';
$.each(result, function (key, item) {
html += '