In this tutorial, I am going to create an example to perform CRUD operation in ASP.NET MVC. I am not using Jquery or AJAX for posting data.

Introduction:

I have just started learning MVC. Then this article will help you a bit in learning MVC. Here I will show you how you can perform CRUD operation in ASP.NET MVC.

Simple CRUD Operation In ASP.NET MVC.

Just follow the steps to complete this session to learn CRUD operation In ASP.NET MVC. First of all, we need to create Database and table to start the example.

Step 1- Open SQL Server and Create a Database.

CREATE DATABASE MVCCRUDDemo

Step 2- Now we need to create a table in the database that we have just created. Run the following script.

USE MVCCRUDDemo
CREATE TABLE [dbo].[Employee]
(
ID INT PRIMARY KEY IDENTITY,
Name VARCHAR(100),
Address VARCHAR(150),
ContactNo VARCHAR(50)
)

Step 3- Now we have finished our job with SQL Server. Open Visual Studio and create an ASP.NET MVC application.

CRUD

 

 

Step 4- Choose an empty template and Click on OK button. Your empty MVC application will look like this.

CRUD

Add Model:

Step 5- Now you need to add a Model. Right Click on the Model folder in SolutionExplorer and add a Class with the name Employee.

CRUD

Step 6- Write following code in Employee Class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MVCCRUDDemo.Models
{
 public class Employee
 {
 public int ID { get; set; }
 public string Name { get; set; }
 public string Address { get; set; }
 public string ContactNo { get; set; }

}
}

Step 7- Right Click on Controllers folders and create a controller with the name Home.

CRUD

Type Home in the textbox and click OK.

CRUD

Your Home Controller will have the following default code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVCCRUDDemo.Controllers
{
 public class HomeController : Controller
 {
 //
 // GET: /Home/

public ActionResult Index()
 {
 return View();
 }

}
}

Perform Create Operation:

Step 8- To Perform Create operation we need to add an Action method with name Create.

public ActionResult Create()
 {
 return View();
 }

Build the application once after creating Model class.

Step 9-  Right Click on the Create action method and add a strongly typed View as shown in the below snapshot. A Strongly type is a View that is Model Bind  Binded. We will discuss more on Strongly typed View in upcoming sessions.

CRUD

CRUD

Your Create View should contain following code:

@model MVCCRUDDemo.Models.Employee

@{
 ViewBag.Title = "Create";
}

<h2>Create</h2>

@using (Html.BeginForm()) {
 @Html.AntiForgeryToken()
 @Html.ValidationSummary(true)

<fieldset>
 <legend>Employee</legend>

<div class="editor-label">
 @Html.LabelFor(model => model.Name)
 </div>
 <div class="editor-field">
 @Html.EditorFor(model => model.Name)
 @Html.ValidationMessageFor(model => model.Name)
 </div>

<div class="editor-label">
 @Html.LabelFor(model => model.Address)
 </div>
 <div class="editor-field">
 @Html.EditorFor(model => model.Address)
 @Html.ValidationMessageFor(model => model.Address)
 </div>

<div class="editor-label">
 @Html.LabelFor(model => model.ContactNo)
 </div>
 <div class="editor-field">
 @Html.EditorFor(model => model.ContactNo)
 @Html.ValidationMessageFor(model => model.ContactNo)
 </div>

<p>
 <input type="submit" value="Create" />
 </p>
 </fieldset>
}

<div>
 @Html.ActionLink("Back to List", "Index")
</div>

Step 10-  To perform Post operation with Create operation we need to add Create Action method with HTTPPost attribute. This Create Action method should also contain  Employee Model as a parameter. Here is code for Post operation:

[HttpPost]
public ActionResult Create(Employee objEmployee)
{
try
{
using (SqlConnection dbCon = new SqlConnection("Data Source=DESKTOP-9VC12LL\\SQLEXPRESS;Integrated Security=MVCCRUDDemo;Integrated Security=true"))
{
using (SqlCommand cmdAddEmployee = new SqlCommand("INSERT INTO [dbo].[Employee] (Name,Address,ContactNo) VALUES(@Name,@Address,@ContactNo)",dbCon))
{
cmdAddEmployee.Parameters.AddWithValue("@Name", objEmployee.Name);
cmdAddEmployee.Parameters.AddWithValue("@Address", objEmployee.Address);
cmdAddEmployee.Parameters.AddWithValue("@ContactNo", objEmployee.ContactNo);
if (dbCon.State == ConnectionState.Closed)
dbCon.Open();
cmdAddEmployee.ExecuteNonQuery();


}
}
}
catch (Exception ex)
{ }

return RedirectToAction("Index");
}

Perform Read Operation:

Step 11- As we have a default Index Action method.  Replace your default Index method with the following code.

public ActionResult Index()
 {
 List<Employee> lstEmployee = new List<Employee>();
 try
 {
 Employee objEmployee = null;
 using (SqlConnection dbCon = new SqlConnection("Data Source=DESKTOP-9VC12LL\\SQLEXPRESS;Integrated Security=MVCCRUDDemo;Integrated Security=true"))
 {
 using (SqlCommand cmdAddEmployee = new SqlCommand("SELECT Name,Address,ContactNo FROM [dbo].[Employee]", dbCon))
 {
 if (dbCon.State == ConnectionState.Closed)
 dbCon.Open();
 using (SqlDataReader drGetEmployee = cmdAddEmployee.ExecuteReader())
 {
 if(drGetEmployee.HasRows)
 {
 while (drGetEmployee.Read())
 {
 objEmployee = new Employee();
 objEmployee.ID = drGetEmployee.GetInt32(0);
 objEmployee.Name = drGetEmployee.GetString(1);
 objEmployee.Address = drGetEmployee.GetString(2);
 objEmployee.ContactNo = drGetEmployee.GetString(3);
 lstEmployee.Add(objEmployee);


 }
 }

 }



 }
 }
 }
 catch (Exception ex)
 { }

 return View(lstEmployee);
 }

Step 13- We have performed code for fetching data from the database. Now we need to render this data on View. Right click on the Index action method and Create a View as shown in the below image.

CRUD

Step 14- Make sure you have following code in Index.cshtml.

@model IEnumerable<MVCCRUDDemo.Models.Employee>

@{
 ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
 @Html.ActionLink("Create New", "Create")
</p>
<table>
 <tr>
 <th>
 @Html.DisplayNameFor(model => model.Name)
 </th>
 <th>
 @Html.DisplayNameFor(model => model.Address)
 </th>
 <th>
 @Html.DisplayNameFor(model => model.ContactNo)
 </th>
 <th></th>
 </tr>

@foreach (var item in Model) {
 <tr>
 <td>
 @Html.DisplayFor(modelItem => item.Name)
 </td>
 <td>
 @Html.DisplayFor(modelItem => item.Address)
 </td>
 <td>
 @Html.DisplayFor(modelItem => item.ContactNo)
 </td>
 <td>
 @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
 @Html.ActionLink("Delete", "Delete", new { id=item.ID })
 </td>
 </tr>
}

</table>

Perform Edit Operation:

Step 15- Declare an Edit action method in Home Controller.

 public ActionResult Edit()
 {
 return View();
 }

Since we need to get Employee Details to edit. Replace the above Edit Action method with the following.

public ActionResult Edit(string ID)
 {
 Employee objEmployee = null;
 try
 {

using (SqlConnection dbCon = new SqlConnection("Data Source=DESKTOP-9VC12LL\\SQLEXPRESS;Integrated Security=MVCCRUDDemo;Integrated Security=true"))
 {
 using (SqlCommand cmdGetEmployeeDetails = new SqlCommand("SELECT ID,Name,Address,ContactNo FROM [dbo].[Employee] WHERE [email protected]",dbCon))
 {
 cmdGetEmployeeDetails.Parameters.AddWithValue("@ID",ID);
 if (dbCon.State == ConnectionState.Closed)
 dbCon.Open();
 using (SqlDataReader drGetEmployeeDetails = cmdGetEmployeeDetails.ExecuteReader())
 {
 if (drGetEmployeeDetails.HasRows)
 {
 while (drGetEmployeeDetails.Read())
 {
 objEmployee = new Employee();
 objEmployee.ID = drGetEmployee.GetInt32(0);
 objEmployee.Name = drGetEmployee.GetString(1);
 objEmployee.Address = drGetEmployee.GetString(2);
 objEmployee.ContactNo = drGetEmployee.GetString(3);
 }
 }
 }


 }
 }
 }
 catch(Exception ex)
 { }
 return View(objEmployee);
 }

Step 16- Right Click on the Edit Action method and add a View as shown in the below image.

CRUD

Make sure you have the following code in Edit.cshtml file.

@model MVCCRUDDemo.Models.Employee

@{
 ViewBag.Title = "Edit";
}

<h2>Edit</h2>

@using (Html.BeginForm()) {
 @Html.AntiForgeryToken()
 @Html.ValidationSummary(true)

<fieldset>
 <legend>Employee</legend>

@Html.HiddenFor(model => model.ID)

<div class="editor-label">
 @Html.LabelFor(model => model.Name)
 </div>
 <div class="editor-field">
 @Html.EditorFor(model => model.Name)
 @Html.ValidationMessageFor(model => model.Name)
 </div>

<div class="editor-label">
 @Html.LabelFor(model => model.Address)
 </div>
 <div class="editor-field">
 @Html.EditorFor(model => model.Address)
 @Html.ValidationMessageFor(model => model.Address)
 </div>

<div class="editor-label">
 @Html.LabelFor(model => model.ContactNo)
 </div>
 <div class="editor-field">
 @Html.EditorFor(model => model.ContactNo)
 @Html.ValidationMessageFor(model => model.ContactNo)
 </div>

<p>
 <input type="submit" value="Save" />
 </p>
 </fieldset>
}

<div>
 @Html.ActionLink("Back to List", "Index")
</div>

Now we need to perform Post operation to Edit Employee Record. Add Edit Action method with HTTPPost attribute in Home Controller.

 [HttpPost]
 public ActionResult Edit(Employee objEmployee)
 {
 try
 {
 using (SqlConnection dbCon = new SqlConnection("Data Source=DESKTOP-9VC12LL\\SQLEXPRESS;Integrated Security=MVCCRUDDemo;Integrated Security=true"))
 {
 using (SqlCommand cmdUpdateEmployee = new SqlCommand("UPDATE [dbo].[Employee] SET [email protected],[email protected],[email protected] WHERE [email protected]",dbCon))
 {
 cmdUpdateEmployee.Parameters.AddWithValue("@ID", objEmployee.ID);
 cmdUpdateEmployee.Parameters.AddWithValue("@Name", objEmployee.Name);
 cmdUpdateEmployee.Parameters.AddWithValue("@Address", objEmployee.Address);
 cmdUpdateEmployee.Parameters.AddWithValue("@ContactNo", objEmployee.ContactNo);
 if (dbCon.State == ConnectionState.Closed)
 dbCon.Open();
 cmdUpdateEmployee.ExecuteNonQuery();


 }
 }
 }
 catch (Exception ex)
 { }
 return RedirectToAction("Index");
 }

Perform Delete Operation:

Step 19- To Perform Delete operation add a Delete action method with HTTPPost attribute and here is the code for this.

public ActionResult Delete(string ID)
 {
 try
 {
 using (SqlConnection dbCon = new SqlConnection("Data Source=DESKTOP-9VC12LL\\SQLEXPRESS;Integrated Security=MVCCRUDDemo;Integrated Security=true"))
 {
 using (SqlCommand cmdDeleteEmployee = new SqlCommand("DELETE FROM [dbo].[Employee] WHERE [email protected]", dbCon))
 {
 cmdDeleteEmployee.Parameters.AddWithValue("@ID", ID);
 if (dbCon.State == ConnectionState.Closed)
 dbCon.Open();
 cmdDeleteEmployee.ExecuteNonQuery();


 }
 }
 }
 catch (Exception ex)
 { }
 return RedirectToAction("Index");
 }


Run the application and check all operations. The First screen you will get your Index View.

CRUD

Click on the Create New Link.

CRUD

You can download the complete source code for the application here.

You must also see the following links:

Introduction to Entity Framework in .NET.

Code First Approach in Entity Framework.

Login Form in ASP.NET MVC.

Web Grid in ASP.NET MVC.

Signalr in ASP.NET MVC

Hope you understand how to perform CRUD Operation in ASP.NET MVC.

Thank You.

 

Leave a Comment