CRUD Operations in MVC using ADO.NET
CRUD stands for Create, Read, Update and Delete: creating, reading, updating and deleting data in a database. Here we use ADO.NET with MVC to perform the CRUD operations.
Problem Statement: As shown in the image below, the data is organised in a grid with three buttons: one to edit the record, one to show its details and one to delete it. We select the data from the database and show it in the grid. There is also a Create New button at the top left; clicking it opens the new-user page, where we can add a user. In this article you will learn how to create, select, update and delete data, step-by-step, with complete code.
When we click Create New, we are taken to the page below, where we can add a user.
When we click Edit, we are taken to the edit page, where we can edit a user.
When we click Details, we are taken to the details page, where we can see the details of a user.
When we click Delete, we are taken to the delete page, where we can delete a user from the database.
Detailed implementation
To implement CRUD, follow the steps below.
- Create an MVC project in Visual Studio.
- Add a User class to the Models folder and add its properties.
- Add an empty controller named User.
- Add a folder named DataAccessLayer, and in it a class named Crudoperations for the ADO.NET code.
- Create a table named tblUsers in the database to save the user records.
- Create stored procedures to select, insert, update and delete users.
- Add the connection string to the Crudoperations class to connect to the database.
- Install the required packages, System.Data and System.Data.SqlClient, from the NuGet Package Manager.
- Add methods to the Crudoperations class to select, insert, update and delete data using ADO.NET.
- Add action methods to the controller for select, insert, update and delete, with HttpGet and HttpPost.
- Add views for the action methods and style them with HTML and CSS.
Create an MVC project and add the folders and classes. The project structure looks like this:
Write the code below in the User model class, and add the System.ComponentModel namespace for the DisplayName attribute.
public class User
{
[DisplayName("User Number")]
public int UserId { get; set; }
[DisplayName("First Name")]
public string Name { get; set; }
[DisplayName("Last Name")]
public string LastName { get; set; }
[DisplayName("User Name")]
public string UserName { get; set; }
public string Password { get; set; }
[DisplayName("Mobile Number")]
public string Mobile { get; set; }
}
Write the code below in the Crudoperations class for inserting, selecting, updating and deleting data in the database using ADO.NET.
public class UserCrudOperation
{
public string connectionString="";
connectionString="Data Source=DESKTOP-1CO7VJ1\\SQLEXPRESS;Initial Catalog=TestDB;
Integrated Security=True";
public List<User> GetUserList()
{
List<User> list = new List<User>();
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "SP_Select_Users";
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
User user = new User();
user.UserId = Convert.ToInt32(reader["UserId"]);
user.Name = Convert.ToString(reader["Name"]);
user.LastName = Convert.ToString(reader["LastName"]);
user.UserName = Convert.ToString(reader["UserName"]);
user.Password = Convert.ToString(reader["Password"]);
user.Mobile = Convert.ToString(reader["Mobile"]);
list.Add(user);
}
return list;
}
public void CreateUser(User user)
{
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "SP_Insert_User";
conn.Open();
cmd.Parameters.AddWithValue("@Name", SqlDbType.NVarChar).Value = user.Name;
cmd.Parameters.AddWithValue("@LastName", SqlDbType.NVarChar).Value = user.LastName;
cmd.Parameters.AddWithValue("@UserName", SqlDbType.NVarChar).Value = user.UserName;
cmd.Parameters.AddWithValue("@Password", SqlDbType.NVarChar).Value = user.Password;
cmd.Parameters.AddWithValue("@Mobile", SqlDbType.NVarChar).Value = user.Mobile;
cmd.ExecuteNonQuery();
}
public User GetUserByUserID(int userId)
{
User user = new User();
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "SP_Select_User_by_UserID";
cmd.Parameters.AddWithValue("@UserId", SqlDbType.Int).Value = userId;
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
user.UserId = Convert.ToInt32(reader["UserId"]);
user.Name = Convert.ToString(reader["Name"]);
user.LastName = Convert.ToString(reader["LastName"]);
user.UserName = Convert.ToString(reader["UserName"]);
user.Password = Convert.ToString(reader["Password"]);
user.Mobile = Convert.ToString(reader["Mobile"]);
}
return user;
}
public void UpdateUser(User user)
{
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "SP_Update_User";
conn.Open();
cmd.Parameters.AddWithValue("@UserId", SqlDbType.Int).Value = user.UserId;
cmd.Parameters.AddWithValue("@Name", SqlDbType.NVarChar).Value = user.Name;
cmd.Parameters.AddWithValue("@LastName", SqlDbType.NVarChar).Value = user.LastName;
cmd.Parameters.AddWithValue("@UserName", SqlDbType.NVarChar).Value = user.UserName;
cmd.Parameters.AddWithValue("@Password", SqlDbType.NVarChar).Value = user.Password;
cmd.Parameters.AddWithValue("@Mobile", SqlDbType.NVarChar).Value = user.Mobile;
cmd.ExecuteNonQuery();
}
public void DeleteUser(int UserId)
{
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "SP_Delete_User";
conn.Open();
cmd.Parameters.AddWithValue("@UserId", SqlDbType.Int).Value = UserId;
cmd.ExecuteNonQuery();
}
}
Write the code below in the User controller for the action methods that list, edit and delete users.
public class UserController : Controller
{
[HttpGet]
public IActionResult UserList()
{
List<User> users = new List<User>();
DataAccessLayer.UserCrudOperation operation = new DataAccessLayer.UserCrudOperation();
users = operation.GetUserList();
return View(users);
}
[HttpGet]
public IActionResult CreateUser()
{
User user = new User();
return View(user);
}
[HttpPost]
public IActionResult CreateUser(User user)
{
DataAccessLayer.UserCrudOperation userCrudOperation = new DataAccessLayer.UserCrudOperation();
userCrudOperation.CreateUser(user);
return RedirectToAction("UserList");
}
[HttpGet]
public IActionResult EditUser(int id)
{
DataAccessLayer.UserCrudOperation operation = new DataAccessLayer.UserCrudOperation();
User user = operation.GetUserList().FirstOrDefault(x=>x.UserId==id);
return View(user);
}
[HttpPost]
public IActionResult EditUser(User user)
{
User userObj = new User();
userObj.UserId =Convert.ToInt32(user.UserId);
userObj.Name = Convert.ToString(user.Name);
userObj.LastName = Convert.ToString(user.LastName);
userObj.UserName = Convert.ToString(user.UserName);
userObj.Password = Convert.ToString(user.Password);
userObj.Mobile = Convert.ToString(user.Mobile);
DataAccessLayer.UserCrudOperation operation = new DataAccessLayer.UserCrudOperation();
operation.UpdateUser(userObj);
return RedirectToAction("UserList");
}
[HttpGet]
public IActionResult UserDetails(int id)
{
DataAccessLayer.UserCrudOperation operation = new DataAccessLayer.UserCrudOperation();
User user = operation.GetUserList().FirstOrDefault(x => x.UserId == id);
return View(user);
}
[HttpGet]
public IActionResult DeleteUser(int id)
{
DataAccessLayer.UserCrudOperation operation = new DataAccessLayer.UserCrudOperation();
User user = operation.GetUserList().FirstOrDefault(x => x.UserId == id);
return View(user);
}
[HttpGet]
public IActionResult DeleteUserbyId(int id)
{
DataAccessLayer.UserCrudOperation operation = new DataAccessLayer.UserCrudOperation();
operation.DeleteUser(id);
return RedirectToAction("UserList");
}
[HttpPost]
public IActionResult DeleteUser(int id,User user)
{
DataAccessLayer.UserCrudOperation operation = new DataAccessLayer.UserCrudOperation();
operation.DeleteUser(id);
return RedirectToAction("UserList");
}
}
View for the Create action method: copy and paste the code below.
The GetList view displays all the users' data on the page.
View for deleting a user: copy and paste the code below.
View for showing a user's details: copy and paste the code below.
View for editing a user by user ID: copy and paste the code below.
Below are the SQL stored procedures used in the CRUD operations.