Sameer Gaikwad CRUD Operation MVC3 SQL Stored Procedure In ASP.NET MVC 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

 
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.
 
Step 1: Execute the following script on your DB.
  1. SET ANSI_NULLS ON  
  2. GO  
  3.   
  4. SET QUOTED_IDENTIFIER ON  
  5. GO  
  6.   
  7. SET ANSI_PADDING ON  
  8. GO  
  9.   
  10. CREATE TABLE[dbo]. [tblStudent](  
  11.   [student_id][int] IDENTITY(1, 1) NOT NULL,  
  12.   [student_name][varchar](50) NOT NULL,  
  13.   [stduent_age][intNOT NULL,  
  14.   [student_gender][varchar](6) NOT NULL,  
  15.   CONSTRAINT[PK_tblStudent] PRIMARY KEY CLUSTERED(  
  16.     [student_id] ASC  
  17.   ) WITH(PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON[PRIMARY]  
  18. ON[PRIMARY]  
  19.   
  20. GO  
  21.   
  22. SET ANSI_PADDING OFF  
  23. 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.










 
 
 
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.   
  8. namespace MVCWithADO {  
  9.     public class RouteConfig {  
  10.         public static void RegisterRoutes(RouteCollection routes) {  
  11.             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  12.   
  13.             routes.MapRoute(  
  14.                 name: "Default",  
  15.                 url: "{controller}/{action}/{id}",  
  16.                 defaults: new { controller = "CRUD", action = "Index", id = UrlParameter.Optional }  
  17.             );  
  18.         }  
  19.     }  
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.
View Purpose
Home.cshtml This is the default view. Loaded when the application launched. Will display all the records in the table
Create.cshtml Displays control’s to insert the record. Will be rendered when the “Add New Record” button is clicked on the “Home.cshtml” view.
Edit.cshtml Displays 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.   
  4. namespace MVCWithADO.Models {  
  5.     public class CRUDModel {  
  6.         /// <summary>    
  7.         /// Get all records from the DB    
  8.         /// </summary>    
  9.         /// <returns>Datatable</returns>    
  10.         public DataTable GetAllStudents() {  
  11.             DataTable dt = new DataTable();  
  12.             string strConString = @ "Data Source=WELCOME-PC\SQLSERVER2008;Initial Catalog=MyDB;Integrated Security=True";  
  13.             using(SqlConnection con = new SqlConnection(strConString)) {  
  14.                 con.Open();  
  15.                 SqlCommand cmd = new SqlCommand("Select * from tblStudent", con);  
  16.                 SqlDataAdapter da = new SqlDataAdapter(cmd);  
  17.                 da.Fill(dt);  
  18.             }  
  19.             return dt;  
  20.         }  
  21.   
  22.         /// <summary>    
  23.         /// Get student detail by Student id    
  24.         /// </summary>    
  25.         /// <param name="intStudentID"></param>    
  26.         /// <returns></returns>    
  27.         public DataTable GetStudentByID(int intStudentID) {  
  28.             DataTable dt = new DataTable();  
  29.   
  30.             string strConString = @ "Data Source=WELCOME-PC\SQLSERVER2008;Initial Catalog=MyDB;Integrated Security=True";  
  31.   
  32.             using(SqlConnection con = new SqlConnection(strConString)) {  
  33.                 con.Open();  
  34.                 SqlCommand cmd = new SqlCommand("Select * from tblStudent where student_id=" + intStudentID, con);  
  35.                 SqlDataAdapter da = new SqlDataAdapter(cmd);  
  36.                 da.Fill(dt);  
  37.             }  
  38.             return dt;  
  39.         }  
  40.   
  41.         /// <summary>    
  42.         /// Update the student details    
  43.         /// </summary>    
  44.         /// <param name="intStudentID"></param>    
  45.         /// <param name="strStudentName"></param>    
  46.         /// <param name="strGender"></param>    
  47.         /// <param name="intAge"></param>    
  48.         /// <returns></returns>    
  49.         public int UpdateStudent(int intStudentID, string strStudentName, string strGender, int intAge) {  
  50.             string strConString = @ "Data Source=WELCOME-PC\SQLSERVER2008;Initial Catalog=MyDB;Integrated Security=True";  
  51.   
  52.             using(SqlConnection con = new SqlConnection(strConString)) {  
  53.                 con.Open();  
  54.                 string query = "Update tblStudent SET student_name=@studname, student_age=@studage , student_gender=@gender where student_id=@studid";  
  55.                 SqlCommand cmd = new SqlCommand(query, con);  
  56.                 cmd.Parameters.AddWithValue("@studname", strStudentName);  
  57.                 cmd.Parameters.AddWithValue("@studage", intAge);  
  58.                 cmd.Parameters.AddWithValue("@gender", strGender);  
  59.                 cmd.Parameters.AddWithValue("@studid", intStudentID);  
  60.                 return cmd.ExecuteNonQuery();  
  61.             }  
  62.         }  
  63.   
  64.         /// <summary>    
  65.         /// Insert Student record into DB    
  66.         /// </summary>    
  67.         /// <param name="strStudentName"></param>    
  68.         /// <param name="strGender"></param>    
  69.         /// <param name="intAge"></param>    
  70.         /// <returns></returns>    
  71.         public int InsertStudent(string strStudentName, string strGender, int intAge) {  
  72.             string strConString = @ "Data Source=WELCOME-PC\SQLSERVER2008;Initial Catalog=MyDB;Integrated Security=True";  
  73.   
  74.             using(SqlConnection con = new SqlConnection(strConString)) {  
  75.                 con.Open();  
  76.                 string query = "Insert into tblStudent (student_name, student_age,student_gender) values(@studname, @studage , @gender)";  
  77.                 SqlCommand cmd = new SqlCommand(query, con);  
  78.                 cmd.Parameters.AddWithValue("@studname", strStudentName);  
  79.                 cmd.Parameters.AddWithValue("@studage", intAge);  
  80.                 cmd.Parameters.AddWithValue("@gender", strGender);  
  81.                 return cmd.ExecuteNonQuery();  
  82.             }  
  83.         }  
  84.   
  85.         /// <summary>    
  86.         /// Delete student based on ID    
  87.         /// </summary>    
  88.         /// <param name="intStudentID"></param>    
  89.         /// <returns></returns>    
  90.         public int DeleteStudent(int intStudentID) {  
  91.             string strConString = @ "Data Source=WELCOME-PC\SQLSERVER2008;Initial Catalog=MyDB;Integrated Security=True";  
  92.   
  93.             using(SqlConnection con = new SqlConnection(strConString)) {  
  94.                 con.Open();  
  95.                 string query = "Delete from tblStudent where student_id=@studid";  
  96.                 SqlCommand cmd = new SqlCommand(query, con);  
  97.                 cmd.Parameters.AddWithValue("@studid", intStudentID);  
  98.                 return cmd.ExecuteNonQuery();  
  99.             }  
  100.         }  
  101.     }  







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.   
  22.         /// <summary>    
  23.         /// Action method, called when the "Add New Record" link clicked    
  24.         /// </summary>    
  25.         /// <returns>Create View</returns>    
  26.         public ActionResult Insert() {  
  27.             return View("Create");  
  28.         }  
  29.   
  30.         /// <summary>    
  31.         /// Action method, called when the user hit "Submit" button    
  32.         /// </summary>    
  33.         /// <param name="frm">Form Collection  Object</param>    
  34.         /// <param name="action">Used to differentiate between "submit" and "cancel"</param>    
  35.         /// <returns></returns>    
  36.         public ActionResult InsertRecord(FormCollection frm, string action) {  
  37.             if (action == "Submit") {  
  38.                 CRUDModel model = new CRUDModel();  
  39.                 string name = frm["txtName"];  
  40.                 int age = Convert.ToInt32(frm["txtAge"]);  
  41.                 string gender = frm["gender"];  
  42.                 int status = model.InsertStudent(name, gender, age);  
  43.                 return RedirectToAction("Index");  
  44.             } else {  
  45.                 return RedirectToAction("Index");  
  46.             }  
  47.         }  
  48.   
  49.         /// <summary>    
  50.         /// Action method called when the user click "Edit" Link    
  51.         /// </summary>    
  52.         /// <param name="StudentID">Student ID</param>    
  53.         /// <returns>Edit View</returns>    
  54.         public ActionResult Edit(int StudentID) {  
  55.             CRUDModel model = new CRUDModel();  
  56.             DataTable dt = model.GetStudentByID(StudentID);  
  57.             return View("Edit", dt);  
  58.         }  
  59.   
  60.         /// <summary>    
  61.         /// Actin method, called when users update the record or cancel the update.    
  62.         /// </summary>    
  63.         /// <param name="frm">Form Collection</param>    
  64.         /// <param name="action">Denotes the action</param>    
  65.         /// <returns>Home view</returns>    
  66.         public ActionResult UpdateRecord(FormCollection frm, string action) {  
  67.             if (action == "Submit") {  
  68.                 CRUDModel model = new CRUDModel();  
  69.                 string name = frm["txtName"];  
  70.                 int age = Convert.ToInt32(frm["txtAge"]);  
  71.                 string gender = frm["gender"];  
  72.                 int id = Convert.ToInt32(frm["hdnID"]);  
  73.                 int status = model.UpdateStudent(id, name, gender, age);  
  74.                 return RedirectToAction("Index");  
  75.             } else {  
  76.                 return RedirectToAction("Index");  
  77.             }  
  78.         }  
  79.   
  80.         /// <summary>    
  81.         /// Action method called when the "Delete" link clicked    
  82.         /// </summary>    
  83.         /// <param name="StudentID">Stutend ID to edit</param>    
  84.         /// <returns>Home view</returns>    
  85.         public ActionResult Delete(int StudentID) {  
  86.             CRUDModel model = new CRUDModel();  
  87.             model.DeleteStudent(StudentID);  
  88.             return RedirectToAction("Index");  
  89.         }  
  90.     }  





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













Create.cshtml
  1. <!DOCTYPE html>  
  2. <html>  
  3.   
  4.     <head>  
  5.         <meta name="viewport" content="width=device-width" />  
  6.         <title>Insert</title>  
  7.     </head>  
  8.   
  9.     <body>  
  10.         <form id="frmDetail" method="post" action="@Url.Action(" InsertRecord")">  
  11.             Enter Name:<input name="txtName" />  
  12.             <br />  
  13.             Enter Age:<input name="txtAge" />  
  14.             <br />  
  15.             Select Gender: <input type="radio" name="gender" value="male" checked>Male  
  16.             <input type="radio" name="gender" value="female">Female  
  17.             <br />  
  18.             <input type="submit" value="Submit" name="action" />  
  19.             <input type="submit" value="Cancel" name="action" />  
  20.         </form>  
  21.     </body>  
  22.   
  23. </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.   
  9.     <head>  
  10.         <script type="text/javascript">  
  11.         </script>  
  12.     </head>  
  13.   
  14.     <body>  
  15.         <form id="frmDetail" method="post" action="@Url.Action(" UpdateRecord")">  
  16.             Enter Name:<input name="txtName" value="@Model.Rows[0][" student_name"]" />  
  17.             <br />  
  18.             Enter Age:<input name="txtAge" value="@Model.Rows[0][" student_age"]" />  
  19.             <br />  
  20.             Select Gender:  
  21.             @if (Model.Rows[0]["student_gender"].ToString().ToLower() == "male")  
  22.             {  
  23.             <input type="radio" name="gender" value="male" checked /> @Html.Raw("Male")  
  24.             <input type="radio" name="gender" value="female" /> @Html.Raw("Female")  
  25.             }  
  26.             else  
  27.             {  
  28.             <input type="radio" name="gender" value="male"> @Html.Raw("Male")  
  29.             <input type="radio" name="gender" value="female" checked /> @Html.Raw("Female")  
  30.             }  
  31.             <input type="hidden" name="hdnID" value="@Model.Rows[0][" student_id"]" />  
  32.             <br />  
  33.             <input type="submit" value="Submit" name="action" />  
  34.             <input type="submit" value="Cancel" name="action" />  
  35.         </form>  
  36.     </body>  
  37.   
  38. </html> 
Readers, I hope you like this article. Let me know your thoughts as comments.

Post a Comment

0 Comments