Background

After awesome response of an published by me in the year 2013: Insert, Update, Delete In GridView Using ASP.Net C#. It now has more than 140 K views, therefore to help beginners I decided to rewrite the article i with stepbystep approach using ASP.NET MVC, since it is a hot topic in the market today. I have written this article focusing on beginners so they can understand the basics of MVC. Please read my previous article using the following links to understand the basics about MVC:
ActionResult in ASP.NET MVC
Creating an ASP.NET MVC Application

Step 1 : Create an MVC Application.

Now let us start with a stepbystep approach from the creation of simple MVC application as in the following:

"Start", then "All Programs" and select "Microsoft Visual Studio 2015".

"File", then "New" and click "Project..." then select "ASP.NET Web Application Template", then provide the Project a name as you wish and click on OK. After clicking, the following window will appear:

As shown in the preceding screenshot, click on Empty template and check MVC option, then click OK. This will create an empty MVC web application whose Solution Explorer will look like the following:

Step 2: Create Model Class

Now let us create the model class named EmpModel.cs by right clicking on model folder as in the following screenshot:

Note: It is not mandatory that Model class should be in Model folder, it is just for better readability you can create this class anywhere in the solution explorer. This can be done by creating different folder name or without folder name or in a separate class library.

EmpModel.cs class code snippet:

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class EmpModel
{
[Display(Name = "Id")]
public int Empid { get; set; } [Required(ErrorMessage = "First name is required.")]
public string Name { get; set; } [Required(ErrorMessage = "City is required.")]
public string City { get; set; } [Required(ErrorMessage = "Address is required.")]
public string Address { get; set; } }

In the above model class we have added some validation on properties with the help of DataAnnotations.

Step 3: Create Controller.

Now let us add the MVC 5 controller as in the following screenshot:


After clicking on Add button it will show the following window. Now specify the Controller name as Employee with suffix Controller as in the following screenshot:

Note: The controller name must be having suffix as 'Controller' after specifying the name of controller.

After clicking on Add button controller is created with by default code that support CRUD operations and later on we can configure it as per our requirements.

Step 4 : Create Table and Stored procedures.

Now before creating the views let us create the table name Employee in database according to our model fields to store the details:


I hope you have created the same table structure as shown above. Now create the stored procedures to insert, update, view and delete the details as in the following code snippet:

  • To Insert Records
 1
2
3
4
5
6
7
8
9
10
Create procedure [dbo].[AddNewEmpDetails]
(
@Name varchar (50),
@City varchar (50),
@Address varchar (50)
)
as
begin
Insert into Employee values(@Name,@City,@Address)
End
  • To View Added Records
1
2
3
4
5
Create Procedure [dbo].[GetEmployees]
as
begin
select *from Employee
End
  • To Update Records
 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Create procedure [dbo].[UpdateEmpDetails]
(
@EmpId int,
@Name varchar (50),
@City varchar (50),
@Address varchar (50)
)
as
begin
Update Employee
set Name=@Name,
City=@City,
Address=@Address
where Id=@EmpId
End
  • To Delete Records
1
2
3
4
5
6
7
8
Create procedure [dbo].[DeleteEmpById]
(
@EmpId int
)
as
begin
Delete from Employee where Id=@EmpId
End

Step 5: Create Repository class.

Now create Repository folder and Add EmpRepository.cs class for database related operations, after adding the solution explorer will look like the following screenshot:

Now create methods in EmpRepository.cs to handle the CRUD operation as in the following screenshot:

  • EmpRepository.cs
  1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
public class EmpRepository
{ private SqlConnection con;
//To Handle connection related activities
private void connection()
{
string constr = ConfigurationManager.ConnectionStrings["getconn"].ToString();
con = new SqlConnection(constr); }
//To Add Employee details
public bool AddEmployee(EmpModel obj)
{ connection();
SqlCommand com = new SqlCommand("AddNewEmpDetails", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("@Name", obj.Name);
com.Parameters.AddWithValue("@City", obj.City);
com.Parameters.AddWithValue("@Address", obj.Address); con.Open();
int i = com.ExecuteNonQuery();
con.Close();
if (i >= 1)
{ return true; }
else
{ return false;
} }
//To view employee details with generic list
public List<EmpModel> GetAllEmployees()
{
connection();
List<EmpModel> EmpList =new List<EmpModel>(); SqlCommand com = new SqlCommand("GetEmployees", con);
com.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(com);
DataTable dt = new DataTable(); con.Open();
da.Fill(dt);
con.Close();
//Bind EmpModel generic list using dataRow
foreach (DataRow dr in dt.Rows)
{ EmpList.Add( new EmpModel { Empid = Convert.ToInt32(dr["Id"]),
Name =Convert.ToString( dr["Name"]),
City = Convert.ToString( dr["City"]),
Address = Convert.ToString(dr["Address"]) } ); } return EmpList; }
//To Update Employee details
public bool UpdateEmployee(EmpModel obj)
{ connection();
SqlCommand com = new SqlCommand("UpdateEmpDetails", con); com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("@EmpId", obj.Empid);
com.Parameters.AddWithValue("@Name", obj.Name);
com.Parameters.AddWithValue("@City", obj.City);
com.Parameters.AddWithValue("@Address", obj.Address);
con.Open();
int i = com.ExecuteNonQuery();
con.Close();
if (i >= 1)
{ return true; }
else
{ return false;
} }
//To delete Employee details
public bool DeleteEmployee(int Id)
{ connection();
SqlCommand com = new SqlCommand("DeleteEmpById", con); com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("@EmpId", Id); con.Open();
int i = com.ExecuteNonQuery();
con.Close();
if (i >= 1)
{ return true; }
else
{ return false;
} }
}

Step 6 : Create Methods into the EmployeeController.cs file.

Now open the EmployeeController.cs and create the following action methods:

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
public class EmployeeController : Controller
{ // GET: Employee/GetAllEmpDetails
public ActionResult GetAllEmpDetails()
{ EmpRepository EmpRepo = new EmpRepository();
ModelState.Clear();
return View(EmpRepo.GetAllEmployees());
}
// GET: Employee/AddEmployee
public ActionResult AddEmployee()
{
return View();
} // POST: Employee/AddEmployee
[HttpPost]
public ActionResult AddEmployee(EmpModel Emp)
{
try
{
if (ModelState.IsValid)
{
EmpRepository EmpRepo = new EmpRepository(); if (EmpRepo.AddEmployee(Emp))
{
ViewBag.Message = "Employee details added successfully";
}
} return View();
}
catch
{
return View();
}
} // GET: Employee/EditEmpDetails/5
public ActionResult EditEmpDetails(int id)
{
EmpRepository EmpRepo = new EmpRepository(); return View(EmpRepo.GetAllEmployees().Find(Emp => Emp.Empid == id)); } // POST: Employee/EditEmpDetails/5
[HttpPost] public ActionResult EditEmpDetails(int id,EmpModel obj)
{
try
{
EmpRepository EmpRepo = new EmpRepository(); EmpRepo.UpdateEmployee(obj); return RedirectToAction("GetAllEmpDetails");
}
catch
{
return View();
}
} // GET: Employee/DeleteEmp/5
public ActionResult DeleteEmp(int id)
{
try
{
EmpRepository EmpRepo = new EmpRepository();
if (EmpRepo.DeleteEmployee(id))
{
ViewBag.AlertMsg = "Employee details deleted successfully"; }
return RedirectToAction("GetAllEmpDetails"); }
catch
{
return View();
}
} }

Step 7: Create Views.

Create the Partial view to Add the employees

To create the Partial View to add Employees, right click on ActionResult method and then click Add view. Now specify the view name, template name and model class in EmpModel.cs and click on Add button as in the following screenshot:

After clicking on Add button it generates the strongly typed view whose code is given below:

  • AddEmployee.cshtml
 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
@model CRUDUsingMVC.Models.EmpModel  

@using (Html.BeginForm())
{ @Html.AntiForgeryToken() <div class="form-horizontal">
<h4>Add Employee</h4>
<div>
@Html.ActionLink("Back to Employee List", "GetAllEmpDetails")
</div>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" }) <div class="form-group">
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
</div>
</div> <div class="form-group">
@Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })
</div>
</div> <div class="form-group">
@Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })
</div>
</div> <div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10" style="color:green">
@ViewBag.Message </div>
</div>
</div> } <script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
  • To View Added Employees

To view the employee details let us create the partial view named GetAllEmpDetails:


Now click on add button, it will create GetAllEmpDetails.cshtml strongly typed view whose code is given below:

  • GetAllEmpDetails.CsHtml
 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
@model IEnumerable<CRUDUsingMVC.Models.EmpModel>  

<p>
@Html.ActionLink("Add New Employee", "AddEmployee")
</p> <table class="table">
<tr> <th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.City)
</th>
<th>
@Html.DisplayNameFor(model => model.Address)
</th>
<th></th>
</tr> @foreach (var item in Model)
{
@Html.HiddenFor(model => item.Empid)
<tr> <td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.City)
</td>
<td>
@Html.DisplayFor(modelItem => item.Address)
</td>
<td>
@Html.ActionLink("Edit", "EditEmpDetails", new { id = item.Empid }) |
@Html.ActionLink("Delete", "DeleteEmp", new { id = item.Empid }, new { onclick = "return confirm('Are sure wants to delete?');" })
</td>
</tr> } </table>

To Update Added Employees

Follow the same procedure and create EditEmpDetails view to edit the employees. After creating the view the code will be like the following:

  • EditEmpDetails.cshtml
 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
@model CRUDUsingMVC.Models.EmpModel  

@using (Html.BeginForm())
{
@Html.AntiForgeryToken() <div class="form-horizontal">
<h4>Update Employee Details</h4>
<hr />
<div>
@Html.ActionLink("Back to Details", "GetAllEmployees")
</div>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.Empid) <div class="form-group">
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
</div>
</div> <div class="form-group">
@Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })
</div>
</div> <div class="form-group">
@Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })
</div>
</div> <div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Update" class="btn btn-default" />
</div>
</div>
</div>
}
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

Step 8 : Configure Action Link to Edit and delete the records as in the following figure:

The above ActionLink I have added in GetAllEmpDetails.CsHtml view because from there we will delete and update the records.

Step 9: Configure RouteConfig.cs to set default action as in the following code snippet:

 1
2
3
4
5
6
7
8
9
10
11
12
13
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Employee", action = "AddEmployee", id = UrlParameter.Optional }
);
}
}

From the above RouteConfig.cs the default action method we have set is AddEmployee. It means that after running the application the AddEmployee view will be executed first.

Now after adding the all model, views and controller our solution explorer will be look like as in the following screenshot:

Step 10: Run the Application

Now run the application the AddEmployee view will be appears are as:

Click on save button, the model state validation will fire, as per validation we have set into the EmpModel.cs class:

Now enter the details and on clicking save button, the records get added into the database and the following message appears.


Now click on Back to Employee List hyperlink, it will be redirected to employee details grid as in the following screenshot:


Now similar to above screenshot, add another record, then the list will be as in the following screenshot:


Now click on Edit button of one of the record, then it will be redirected to Edit view as in the following screenshot:


Now click on Update button, on clicking, the records will be updated into the database. Click Back to Details hyperlink then it will be redirected to the Employee list table with updated records as in the following screenshot:


Now click on delete button for one of the records, then the following confirmation box appears (we have set configuration in ActionLink):


Now click on OK button, then the updated Employee list table will be like the following screenshot:


From the preceding examples we have learned how to implement CRUD operations in ASP.NET MVC using ADO.NET.

Note:

  • Configure the database connection in the web.config file depending on your database server location.
  • Download the Zip file of the sample application for a better understanding .
  • Since this is a demo, it might not be using proper standards, so improve it depending on your skills
  • This application is created completely focusing on beginners.

Summary

My next article explains the types of controllers in MVC. I hope this article is useful for all readers. If you have any suggestion then please contact me.

· EOF ·

CRUD Operations In ASP.NET MVC 5 Using ADO.NET的更多相关文章

  1. [转]Enabling CRUD Operations in ASP.NET Web API 1

    本文转自:https://docs.microsoft.com/en-us/aspnet/web-api/overview/older-versions/creating-a-web-api-that ...

  2. ASP.NET MVC+JQueryEasyUI1.4+ADO.NET Demo

    1.JQueryEasyUI使用 JQuery EasyUI中文官网:http://www.jeasyui.net/ JQuery EasyUI中文官网下载地址:http://www.jeasyui. ...

  3. 《Entity Framework 6 Recipes》中文翻译系列 (20) -----第四章 ASP.NET MVC中使用实体框架之在MVC中构建一个CRUD示例

    翻译的初衷以及为什么选择<Entity Framework 6 Recipes>来学习,请看本系列开篇 第四章  ASP.NET MVC中使用实体框架 ASP.NET是一个免费的Web框架 ...

  4. [转]ASP.NET MVC 2: Model Validation

    本文转自:http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx?CommentPo ...

  5. 【转】ASP.NET MVC教程

    转自:http://www.cnblogs.com/QLeelulu/category/123326.html ASP.NET MVC的最佳实践与性能优化的文章 摘要: 就一些文章链接,就不多废话了. ...

  6. Asp.net mvc 5 CRUD代码自动生成工具- vs.net 2013 Saffolding功能扩展

    Asp.net mvc 5 CRUD代码自动生成工具 -Visual Studio.net2013 Saffolding功能扩展 上次做过一个<Asp.net webform scaffoldi ...

  7. 【ASP.NET MVC 5】第27章 Web API与单页应用程序

    注:<精通ASP.NET MVC 3框架>受到了出版社和广大读者的充分肯定,这让本人深感欣慰.目前该书的第4版不日即将出版,现在又已开始第5版的翻译,这里先贴出该书的最后一章译稿,仅供大家 ...

  8. Using the Repository Pattern with ASP.NET MVC and Entity Framework

    原文:http://www.codeguru.com/csharp/.net/net_asp/mvc/using-the-repository-pattern-with-asp.net-mvc-and ...

  9. ASP.NET MVC和Web API中的Angular2 - 第2部分

    下载源码 内容 第1部分:Visual Studio 2017中的Angular2设置,基本CRUD应用程序,第三方模态弹出控件 第2部分:使用Angular2管道进行过滤/搜索,全局错误处理,调试客 ...

随机推荐

  1. [WinAPI] API 1 [桌面上画一个简单彩色图形]

    #include<Windows.h> void GdiOut(HDC hdc); int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hP ...

  2. C++ 重载操作符与转换

    <C++ Primer 4th>读书笔记 重载操作符是具有特殊名称的函数:保留字 operator 后接需定义的操作符号. Sales_item operator+(const Sales ...

  3. 使用grunt打包ueditor源代码

    支持版本支持 UEditor 1.3.0+ 的版本 使用方法1.线上下载ueditor下载地址:ueditor,要下载"完整版 + 源码" 2.安装nodejs下载nodejs并安 ...

  4. Java CAS 和ABA问题

    独占锁:是一种悲观锁,synchronized就是一种独占锁,会导致其它所有需要锁的线程挂起,等待持有锁的线程释放锁. 乐观锁:每次不加锁,假设没有冲突去完成某项操作,如果因为冲突失败就重试,直到成功 ...

  5. paip.mysql 全文索引查询空白解决

    paip.mysql 全文索引查询空白解决   或者  Incorrect key file for table: \'%s\'. Try to repair it    作者Attilax  艾龙, ...

  6. paip.获取proxool的配置 xml读取通过jdk xml 初始化c3c0在代码中总结

    paip.获取proxool的配置  xml读取通过jdk xml 初始化c3c0在代码中  xml读取通过jdk xml 初始化c3c0在代码中.. ... 作者Attilax  艾龙,  EMAI ...

  7. CreateJSのeasel.js(一)

    CreateJS是基于HTML5开发的一套模块化的库和工具. 基于这些库,可以非常快捷地开发出基于HTML5的游戏.动画和交互应用. CreateJS为CreateJS库,可以说是一款为HTML5游戏 ...

  8. 解决ScrollView嵌套ListView,ListView填充容器后,界面自动滚动回顶部的问题

    1.scrollView.scrollTo(0,0),有时可以,有时不行: 2.listView.post(new Runnable() {                               ...

  9. 2013年的一些常用PHP資源整理下載

    這些資源基本上都是一些免積分或只需要1個積分就能下載的資源,經過整理篩選最後分享給大家,希望大家喜歡: PHP手册(chm) http://download.csdn.net/detail/u0118 ...

  10. (转)新手必看:HighCharts几个基础问答

    转自:http://bbs.hcharts.cn/article-21-1.html