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 |