Sameer Gaikwad CRUD Operations In ASP.NET MVC Using ADO.NET

Sameer Gaikwad
9 min readMar 14, 2022

--

Follow me Sameer Gaikwad then follow the link below! 👉 💯day challenge 📩 Reach out to me on Twitter or Linkedin, or Blogspot if you want to discuss this further. :)

MS SQL SERVER

Getting Started with SQL

Asp.Net Core MVC with Bootstrap

ASP.NET Core Web App with Blazor

Microsoft Ado.Net Entity Framework

ASP.NET MVC 5 with Bootstrap

ASP.Net Interview Questions

JavaScript Interview Questions

Sameer Gaikwad CRUD Operation SQL stored procedure mesameergaikwad

In this post, I’m going to discuss the CRUD (Create, Read, Update, and Delete) Operations in an ASP.NET MVC application by using raw ADO.NET. Most of the new learners, who started to learn MVC asked this frequently. That’s the main reason I wrote this tutorial. In this article, I’m going to explain the step-by-step procedure from DB table creation to all MVC files.

check out my blog post

check out the GitHub project link

Software Requirements

For this particular application, I have used the following configuration:

  1. Visual Studio 2015
  2. SQL Server 2008

In order to keep my hand clean, I have used a simple table to do the CRUD operation. full article check here read more

Step 1: Execute the following script on your DB.

  1. SET ANSI_NULLS ON
  2. GO
  3. SET QUOTED_IDENTIFIER ON
  4. GO
  5. SET ANSI_PADDING ON
  6. GO
  7. CREATE TABLE[dbo]. [tblStudent](
  8. [student_id][int] IDENTITY(1, 1) NOT NULL,
  9. [student_name][varchar](50) NOT NULL,
  10. [stduent_age][int] NOT NULL,
  11. [student_gender][varchar](6) NOT NULL,
  12. CONSTRAINT[PK_tblStudent] PRIMARY KEY CLUSTERED(
  13. [student_id] ASC
  14. ) WITH(PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON[PRIMARY]
  15. ) ON[PRIMARY]
  16. GO
  17. SET ANSI_PADDING OFF
  18. GO

Step 2: Create an “Empty” ASP.NET MVC application in Visual Studio 2015.

Step 3:

Add an “Empty” Controller by right-clicking on the “Controller” folder. Select “Add” then select “Controller..”. In the popup select “MVC 5 Controller”, then click “Add”. In the next popup, you should give the name “CRUDController”.

After adding the controller, you may notice as per the “convention” in ASP.NET MVC under the “Views” folder, a new folder named “CRUD” was also created. full article check here read more

Step 4:

Our DB access code is going to be placed inside the “Models” folder. The model is just a “Class” file. So we are going to create a Model class for our purpose as below:

  1. Right-click on the “Model” folder. In the context menu select “Add” then choose “New item..”.
  2. In the popup, select “Code” then choose “Class” name the class file as “CRUDModel” then click “Add”. That’s all!

Step 5:

Till now we created classes for “Controller” and “Model”. We didn’t create any views till now. In this step, we are going to create a view, which is going to act as a “home” page for our application. In order to create the view:

  1. Right-click on the “CRUD” folder under the “Views” folder in the context menu select “Add” then choose “View..”.
  2. In the popup, give “View name” and uncheck the “Use a layout page” checkbox. Finally, click the “Add” button.

Step 6:

We don’t have a controller named “Default”, which is specified in the “RouteConfig.cs” file. We need to change the controller’s name to “CRUD”, in the default route values.

Route.config

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Mvc;
  6. using System.Web.Routing;
  7. namespace MVCWithADO {
  8. public class RouteConfig {
  9. public static void RegisterRoutes(RouteCollection routes) {
  10. routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);
  11. routes.MapRoute(
  12. name: “Default”,
  13. url: “{controller}/{action}/{id}”,
  14. defaults: new { controller = “CRUD”, action = “Index”, id = UrlParameter.Optional }
  15. );
  16. }
  17. }
  18. }

After the above change, just press F5 in Visual Studio, to verify that our application works fine without any error.

Step 7:

In order to achieve the complete CRUD operation, I’m going to add a number of views as described in Step 5. Here is the complete list of views and their purpose.

ViewPurposeHome.cshtmlThis is the default view. Loaded when the application launched. Will display all the records in the tableCreate.cshtmlDisplays control’s to insert the record. Will be rendered when the “Add New Record” button is clicked on the “Home.cshtml” view.Edit.cshtmlDisplays control’s to edit the record. Will be rendered when the “Edit” button is clicked on the “Home.cshtml” view.

Step 8:

The model class contains all the “Data Access” logic. In other words, it will interact with the Database and give it back to “View” through “Controller”.

CRUDModel.cs

  1. using System.Data;
  2. using System.Data.SqlClient;
  3. namespace MVCWithADO.Models {
  4. public class CRUDModel {
  5. /// <summary>
  6. /// Get all records from the DB
  7. /// </summary>
  8. /// <returns>Datatable</returns>
  9. public DataTable GetAllStudents() {
  10. DataTable dt = new DataTable();
  11. string strConString = @ “Data Source=WELCOME-PC\SQLSERVER2008;Initial Catalog=MyDB;Integrated Security=True”;
  12. using(SqlConnection con = new SqlConnection(strConString)) {
  13. con.Open();
  14. SqlCommand cmd = new SqlCommand(“Select * from tblStudent”, con);
  15. SqlDataAdapter da = new SqlDataAdapter(cmd);
  16. da.Fill(dt);
  17. }
  18. return dt;
  19. }
  20. /// <summary>
  21. /// Get student detail by Student id
  22. /// </summary>
  23. /// <param name=”intStudentID”></param>
  24. /// <returns></returns>
  25. public DataTable GetStudentByID(int intStudentID) {
  26. DataTable dt = new DataTable();
  27. string strConString = @ “Data Source=WELCOME-PC\SQLSERVER2008;Initial Catalog=MyDB;Integrated Security=True”;
  28. using(SqlConnection con = new SqlConnection(strConString)) {
  29. con.Open();
  30. SqlCommand cmd = new SqlCommand(“Select * from tblStudent where student_id=” + intStudentID, con);
  31. SqlDataAdapter da = new SqlDataAdapter(cmd);
  32. da.Fill(dt);
  33. }
  34. return dt;
  35. }
  36. /// <summary>
  37. /// Update the student details
  38. /// </summary>
  39. /// <param name=”intStudentID”></param>
  40. /// <param name=”strStudentName”></param>
  41. /// <param name=”strGender”></param>
  42. /// <param name=”intAge”></param>
  43. /// <returns></returns>
  44. public int UpdateStudent(int intStudentID, string strStudentName, string strGender, int intAge) {
  45. string strConString = @ “Data Source=WELCOME-PC\SQLSERVER2008;Initial Catalog=MyDB;Integrated Security=True”;
  46. using(SqlConnection con = new SqlConnection(strConString)) {
  47. con.Open();
  48. string query = “Update tblStudent SET student_name=@studname, student_age=@studage , student_gender=@gender where student_id=@studid”;
  49. SqlCommand cmd = new SqlCommand(query, con);
  50. cmd.Parameters.AddWithValue(“@studname”, strStudentName);
  51. cmd.Parameters.AddWithValue(“@studage”, intAge);
  52. cmd.Parameters.AddWithValue(“@gender”, strGender);
  53. cmd.Parameters.AddWithValue(“@studid”, intStudentID);
  54. return cmd.ExecuteNonQuery();
  55. }
  56. }
  57. /// <summary>
  58. /// Insert Student record into DB
  59. /// </summary>
  60. /// <param name=”strStudentName”></param>
  61. /// <param name=”strGender”></param>
  62. /// <param name=”intAge”></param>
  63. /// <returns></returns>
  64. public int InsertStudent(string strStudentName, string strGender, int intAge) {
  65. string strConString = @ “Data Source=WELCOME-PC\SQLSERVER2008;Initial Catalog=MyDB;Integrated Security=True”;
  66. using(SqlConnection con = new SqlConnection(strConString)) {
  67. con.Open();
  68. string query = “Insert into tblStudent (student_name, student_age,student_gender) values(@studname, @studage , @gender)”;
  69. SqlCommand cmd = new SqlCommand(query, con);
  70. cmd.Parameters.AddWithValue(“@studname”, strStudentName);
  71. cmd.Parameters.AddWithValue(“@studage”, intAge);
  72. cmd.Parameters.AddWithValue(“@gender”, strGender);
  73. return cmd.ExecuteNonQuery();
  74. }
  75. }
  76. /// <summary>
  77. /// Delete student based on ID
  78. /// </summary>
  79. /// <param name=”intStudentID”></param>
  80. /// <returns></returns>
  81. public int DeleteStudent(int intStudentID) {
  82. string strConString = @ “Data Source=WELCOME-PC\SQLSERVER2008;Initial Catalog=MyDB;Integrated Security=True”;
  83. using(SqlConnection con = new SqlConnection(strConString)) {
  84. con.Open();
  85. string query = “Delete from tblStudent where student_id=@studid”;
  86. SqlCommand cmd = new SqlCommand(query, con);
  87. cmd.Parameters.AddWithValue(“@studid”, intStudentID);
  88. return cmd.ExecuteNonQuery();
  89. }
  90. }
  91. }
  92. }

CRUDController.cs

In an MVC application, controller is the entry point. The following code contains all the action methods for the complete CRUD operation.

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Mvc;
  6. using System.Data;
  7. using System.Data.SqlClient;
  8. using MVCWithADO.Models;
  9. namespace MVCWithADO.Controllers {
  10. public class CRUDController: Controller {
  11. /// <summary>
  12. /// First Action method called when page loads
  13. /// Fetch all the rows from DB and display it
  14. /// </summary>
  15. /// <returns>Home View</returns>
  16. public ActionResult Index() {
  17. CRUDModel model = new CRUDModel();
  18. DataTable dt = model.GetAllStudents();
  19. return View(“Home”, dt);
  20. }
  21. /// <summary>
  22. /// Action method, called when the “Add New Record” link clicked
  23. /// </summary>
  24. /// <returns>Create View</returns>
  25. public ActionResult Insert() {
  26. return View(“Create”);
  27. }
  28. /// <summary>
  29. /// Action method, called when the user hit “Submit” button
  30. /// </summary>
  31. /// <param name=”frm”>Form Collection Object</param>
  32. /// <param name=”action”>Used to differentiate between “submit” and “cancel”</param>
  33. /// <returns></returns>
  34. public ActionResult InsertRecord(FormCollection frm, string action) {
  35. if (action == “Submit”) {
  36. CRUDModel model = new CRUDModel();
  37. string name = frm[“txtName”];
  38. int age = Convert.ToInt32(frm[“txtAge”]);
  39. string gender = frm[“gender”];
  40. int status = model.InsertStudent(name, gender, age);
  41. return RedirectToAction(“Index”);
  42. } else {
  43. return RedirectToAction(“Index”);
  44. }
  45. }
  46. /// <summary>
  47. /// Action method called when the user click “Edit” Link
  48. /// </summary>
  49. /// <param name=”StudentID”>Student ID</param>
  50. /// <returns>Edit View</returns>
  51. public ActionResult Edit(int StudentID) {
  52. CRUDModel model = new CRUDModel();
  53. DataTable dt = model.GetStudentByID(StudentID);
  54. return View(“Edit”, dt);
  55. }
  56. /// <summary>
  57. /// Actin method, called when users update the record or cancel the update.
  58. /// </summary>
  59. /// <param name=”frm”>Form Collection</param>
  60. /// <param name=”action”>Denotes the action</param>
  61. /// <returns>Home view</returns>
  62. public ActionResult UpdateRecord(FormCollection frm, string action) {
  63. if (action == “Submit”) {
  64. CRUDModel model = new CRUDModel();
  65. string name = frm[“txtName”];
  66. int age = Convert.ToInt32(frm[“txtAge”]);
  67. string gender = frm[“gender”];
  68. int id = Convert.ToInt32(frm[“hdnID”]);
  69. int status = model.UpdateStudent(id, name, gender, age);
  70. return RedirectToAction(“Index”);
  71. } else {
  72. return RedirectToAction(“Index”);
  73. }
  74. }
  75. /// <summary>
  76. /// Action method called when the “Delete” link clicked
  77. /// </summary>
  78. /// <param name=”StudentID”>Stutend ID to edit</param>
  79. /// <returns>Home view</returns>
  80. public ActionResult Delete(int StudentID) {
  81. CRUDModel model = new CRUDModel();
  82. model.DeleteStudent(StudentID);
  83. return RedirectToAction(“Index”);
  84. }
  85. }
  86. }

Views

Views are a combination of markup as well as server-side code. As you noticed the views “Home” and “Edit” take the ADO.NET object Datatable as a model. Also, for simplicity, I don’t use “Layout”.

Home.cshtml

  1. @using System.Data
  2. @using System.Data.SqlClient
  3. @model System.Data.DataTable
  4. @{
  5. Layout = null;
  6. }
  7. <!DOCTYPE html>
  8. <html>
  9. <head>
  10. <meta name=”viewport” content=”width=device-width” />
  11. <title>Home</title>
  12. </head>
  13. <body>
  14. <form method=”post” name=”Display”>
  15. <h2>Home</h2>
  16. @Html.ActionLink(“Add New Record”, “Insert”)
  17. <br />
  18. @{
  19. if (Model.Rows.Count > 0)
  20. {
  21. <table border=”1">
  22. <thead>
  23. <tr>
  24. <td>
  25. Student ID
  26. </td>
  27. <td>
  28. Name
  29. </td>
  30. <td>
  31. Age
  32. </td>
  33. <td>Gender</td>
  34. </tr>
  35. </thead>
  36. @foreach (DataRow dr in Model.Rows)
  37. {
  38. <tr>
  39. <td>@dr[“student_id”].ToString() </td>
  40. <td>@dr[“student_name”].ToString() </td>
  41. <td>@dr[“student_age”].ToString() </td>
  42. <td>@dr[“student_gender”].ToString() </td>
  43. <td>@Html.ActionLink(“Edit “, “Edit”, new { StudentID = dr[“student_id”].ToString() })</td>
  44. <td>@Html.ActionLink(“| Delete”, “Delete”, new { StudentID = dr[“student_id”].ToString() })</td>
  45. </tr>
  46. }
  47. </table>
  48. <br />
  49. }
  50. else
  51. {
  52. <span> No records found!!</span>
  53. }
  54. }
  55. </form>
  56. </body>
  57. </html>

Create.cshtml

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta name=”viewport” content=”width=device-width” />
  5. <title>Insert</title>
  6. </head>
  7. <body>
  8. <form id=”frmDetail” method=”post” action=”@Url.Action(“ InsertRecord”)”>
  9. Enter Name:<input name=”txtName” />
  10. <br />
  11. Enter Age:<input name=”txtAge” />
  12. <br />
  13. Select Gender: <input type=”radio” name=”gender” value=”male” checked>Male
  14. <input type=”radio” name=”gender” value=”female”>Female
  15. <br />
  16. <input type=”submit” value=”Submit” name=”action” />
  17. <input type=”submit” value=”Cancel” name=”action” />
  18. </form>
  19. </body>
  20. </html>

Edit.cshtml

  1. @using System.Data
  2. @using System.Data.SqlClient
  3. @model System.Data.DataTable
  4. @{
  5. ViewBag.Title = “EditView”;
  6. }
  7. <html>
  8. <head>
  9. <script type=”text/javascript”>
  10. </script>
  11. </head>
  12. <body>
  13. <form id=”frmDetail” method=”post” action=”@Url.Action(“ UpdateRecord”)”>
  14. Enter Name:<input name=”txtName” value=”@Model.Rows[0][“ student_name”]” />
  15. <br />
  16. Enter Age:<input name=”txtAge” value=”@Model.Rows[0][“ student_age”]” />
  17. <br />
  18. Select Gender:
  19. @if (Model.Rows[0][“student_gender”].ToString().ToLower() == “male”)
  20. {
  21. <input type=”radio” name=”gender” value=”male” checked /> @Html.Raw(“Male”)
  22. <input type=”radio” name=”gender” value=”female” /> @Html.Raw(“Female”)
  23. }
  24. else
  25. {
  26. <input type=”radio” name=”gender” value=”male”> @Html.Raw(“Male”)
  27. <input type=”radio” name=”gender” value=”female” checked /> @Html.Raw(“Female”)
  28. }
  29. <input type=”hidden” name=”hdnID” value=”@Model.Rows[0][“ student_id”]” />
  30. <br />
  31. <input type=”submit” value=”Submit” name=”action” />
  32. <input type=”submit” value=”Cancel” name=”action” />
  33. </form>
  34. </body>
  35. </html>

Readers, I hope you like this article. Let me know your thoughts as comments.

#sameergaikwadbymesameergaikwad #sameergaikwadcrudoperation #sameergaikwadmvccrudoperation #sameergaikwadjoinsinsqlserver #sameergaikwadsqlstoredprocedure #sameergaikwadsqltolinq

--

--

Sameer Gaikwad

#mesameergaikwad Sameer Gaikwad on mesameergaikwad MVC web service crud operation join SQL to LINQ Stored Procedure WEB API Entity Framework