Sameer Gaikwad CRUD Operation MVC Entity Framework SQL Stored Procedure In ASP.NET MVC mesameergaikwad

In this article you will learn:
  1. ASP.NET MVC 5 with ADO.Net Connectivity
  2. CRUD – CREATE, READ, UPDATE and DELETE Operation

In this article you are going to learn how to Insert, Update and Delete Records in ASP.NET MVC 5 without using heavy entity framework. This article uses pure ADO.Net commands to work with SQL database. You will learn MVC 5 application with ado.net connectivity with complete pictorial guide and step by step examples. Once you complete this article, I promise, you will be able to write your own customize code in MVC 5. If you are beginners or trying to learn MVC, then don't skip this tutorial, because this article contains complete programming example with screen shot. As I understand the need of beginners that they require complete programming example instead of part of the code.

Let's Start ASP.NET MVC 5 with CRUD Operation

In this example, I am going to create a simple student registration form in MVC5 using CRUD (Create, Read, Update and Delete) Operation. In this tutorial, I haven’t used heavy entity framework and gives you a way to write transparent ADO.NET Connectivity.

  
1. Create New ASP.NET MVC 5 Project

1. Open Visual Studio 2015. Click on File New Project.
2. Select Web in the template section and select ASP.NET Web Application. Give name CRUDinMVC and click OK.
3. A template windows will open. Select Empty template and check MVC checkbox as described in the given picture.

4. Your project will open for develop. If you see AZURE Hosting window before opening the project, gently cancel it.
 
2. Create Model Class
1. Right click on Models Folder Add Class. Select class in middle pane and create new class StudentModel.cs.

2. Your StudentModel.cs class should be look like this code snippets.
  1. using System.ComponentModel.DataAnnotations;
  2.  
  3. namespace CRUDinMVC.Models
  4. {
  5. public class StudentModel
  6. {
  7. [Display(Name = "Id")]
  8. public int Id { get; set; }
  9.  
  10. [Required(ErrorMessage = "First name is required.")]
  11. public string Name { get; set; }
  12.  
  13. [Required(ErrorMessage = "City is required.")]
  14. public string City { get; set; }
  15.  
  16. [Required(ErrorMessage = "Address is required.")]
  17. public string Address { get; set; }
  18. }
  19. }

 
3. Create Controller
1. Right Click on Controllers Folder Add Controller.

2. Scaffold window will open. Here, choose MVC 5 Controller with read/write actions and click Add button.

3. Give name StudentController and click Add.

 
4. Create Database, Table and Store Procedure
CREATE OR SELECT DATABASE
1. Open Server Explorer. Go to View Server Explorer.
2. Right Click on Data Connections Create New SQL Server Database.
3. Create StudentDB database as the picture below.

4. If you have already a database then you can make connection with existing database. Right Click on Data Connections Add Connection
5. Select database as picture below

CREATE StudentReg TABLE
1. Now create a Table StudentReg in database according to models. Expand StudentDB database in Server Explorer and Right Click on Table and then select Add New Table.

2. Make Table exactly the same as described in the picture. Go to Table Properties and must set Id in Identity column and StudentReg in Name Column.


3. Table Scripts
  1. CREATE TABLE [dbo].[StudentReg]
  2. (
  3. [Id] INT NOT NULL PRIMARY KEY IDENTITY,
  4. [Name] NVARCHAR(50) NULL,
  5. [City] NVARCHAR(50) NULL,
  6. [Address] NVARCHAR(100) NULL
  7. )

4. After finishing table designing click on Update button to save table.
Create Store Procedure for CRUDCreate, Read, Update and Delete Operation.

Open New Query Window. Right Click on database name in Server Explorer and select New Query. Now, Paste following code snippets one by one and execute code by pressing Ctrl + Shift + E or clicking on Execute icon on the top left corner of query window.



1. Insert Records – Store Procedure
  1. Create procedure [dbo].[AddNewStudent]
  2. (
  3. @Name nvarchar (50),
  4. @City nvarchar (50),
  5. @Address nvarchar (100)
  6. )
  7. as
  8. begin
  9. Insert into StudentReg values(@Name,@City,@Address)
  10. End


2. View Added Records – Store Procedure
  1. Create Procedure [dbo].[GetStudentDetails]
  2. as
  3. begin
  4. select * from StudentReg
  5. End


3. Update Records – Store Procedure
  1. Create procedure [dbo].[UpdateStudentDetails]
  2. (
  3. @StdId int,
  4. @Name nvarchar (50),
  5. @City nvarchar (50),
  6. @Address nvarchar (100)
  7. )
  8. as
  9. begin
  10. Update StudentReg
  11. set Name=@Name,
  12. City=@City,
  13. Address=@Address
  14. where Id=@StdId
  15. End


4. Delete Records – Store Procedure
  1. Create procedure [dbo].[DeleteStudent]
  2. (
  3. @StdId int
  4. )
  5. as
  6. begin
  7. Delete from StudentReg where Id=@StdId
  8. End

After Creating all Store Procedure your Server Explorer will look like:

 
5. Add Connection String in Web.config file.

1. Add Connection String in Web.config file. You can find connection string in the database properties. Right click on Database Name and Select Properties. Copy Connection String and keep it.

2. Open Root Web.config file and paste following code just before </Configuratin>.
  1. <connectionStrings>
  2. <add name="StudentConn" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=StudentDB;Integrated Security=True;Pooling=False"/>
  3. </connectionStrings>


 
6. Create StudentDBHandle.cs class for handling all the database operations.
Paste Following code in StudentDBHandle.cs class.
1. Right click on Models folder Add Class. Create new class StudentDBHandle.cs
2. Now paste following code in this file.
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Data.SqlClient;
  5. using System.Configuration;
  6.  
  7. namespace CRUDinMVC.Models
  8. {
  9. public class StudentDBHandle
  10. {
  11. private SqlConnection con;
  12. private void connection()
  13. {
  14. string constring = ConfigurationManager.ConnectionStrings["studentconn"].ToString();
  15. con = new SqlConnection(constring);
  16. }
  17.  
  18. // **************** ADD NEW STUDENT *********************
  19. public bool AddStudent(StudentModel smodel)
  20. {
  21. connection();
  22. SqlCommand cmd = new SqlCommand("AddNewStudent", con);
  23. cmd.CommandType = CommandType.StoredProcedure;
  24.  
  25. cmd.Parameters.AddWithValue("@Name", smodel.Name);
  26. cmd.Parameters.AddWithValue("@City", smodel.City);
  27. cmd.Parameters.AddWithValue("@Address", smodel.Address);
  28.  
  29. con.Open();
  30. int i = cmd.ExecuteNonQuery();
  31. con.Close();
  32.  
  33. if (i >= 1)
  34. return true;
  35. else
  36. return false;
  37. }
  38.  
  39. // ********** VIEW STUDENT DETAILS ********************
  40. public List<StudentModel> GetStudent()
  41. {
  42. connection();
  43. List<StudentModel> studentlist = new List<StudentModel>();
  44.  
  45. SqlCommand cmd = new SqlCommand("GetStudentDetails", con);
  46. cmd.CommandType = CommandType.StoredProcedure;
  47. SqlDataAdapter sd = new SqlDataAdapter(cmd);
  48. DataTable dt = new DataTable();
  49.  
  50. con.Open();
  51. sd.Fill(dt);
  52. con.Close();
  53.  
  54. foreach(DataRow dr in dt.Rows)
  55. {
  56. studentlist.Add(
  57. new StudentModel
  58. {
  59. Id = Convert.ToInt32(dr["Id"]),
  60. Name = Convert.ToString(dr["Name"]),
  61. City = Convert.ToString(dr["City"]),
  62. Address = Convert.ToString(dr["Address"])
  63. });
  64. }
  65. return studentlist;
  66. }
  67.  
  68. // ***************** UPDATE STUDENT DETAILS *********************
  69. public bool UpdateDetails(StudentModel smodel)
  70. {
  71. connection();
  72. SqlCommand cmd = new SqlCommand("UpdateStudentDetails", con);
  73. cmd.CommandType = CommandType.StoredProcedure;
  74.  
  75. cmd.Parameters.AddWithValue("@StdId", smodel.Id);
  76. cmd.Parameters.AddWithValue("@Name", smodel.Name);
  77. cmd.Parameters.AddWithValue("@City", smodel.City);
  78. cmd.Parameters.AddWithValue("@Address", smodel.Address);
  79.  
  80. con.Open();
  81. int i = cmd.ExecuteNonQuery();
  82. con.Close();
  83.  
  84. if (i >= 1)
  85. return true;
  86. else
  87. return false;
  88. }
  89.  
  90. // ********************** DELETE STUDENT DETAILS *******************
  91. public bool DeleteStudent(int id)
  92. {
  93. connection();
  94. SqlCommand cmd = new SqlCommand("DeleteStudent", con);
  95. cmd.CommandType = CommandType.StoredProcedure;
  96.  
  97. cmd.Parameters.AddWithValue("@StdId", id);
  98.  
  99. con.Open();
  100. int i = cmd.ExecuteNonQuery();
  101. con.Close();
  102.  
  103. if (i >= 1)
  104. return true;
  105. else
  106. return false;
  107. }
  108. }
  109. }


 
7. Add Action Method in StudentController
Open StudentController and add the following action methods. Here, I am going to add four action methods for following purpose.
a. Index() - Showing All Student Details
b. Create() - Adding New Student
c. Edit () - Edit or Update Student Details
d. Delete () - Delete Student Details

  1. using System.Web.Mvc;
  2. using CRUDinMVC.Models;
  3.  
  4. namespace CRUDinMVC.Controllers
  5. {
  6. public class StudentController : Controller
  7. {
  8. // 1. *************RETRIEVE ALL STUDENT DETAILS ******************
  9. // GET: Student
  10. public ActionResult Index()
  11. {
  12. StudentDBHandle dbhandle = new StudentDBHandle();
  13. ModelState.Clear();
  14. return View(dbhandle.GetStudent());
  15. }
  16.  
  17. // 2. *************ADD NEW STUDENT ******************
  18. // GET: Student/Create
  19. public ActionResult Create()
  20. {
  21. return View();
  22. }
  23.  
  24. // POST: Student/Create
  25. [HttpPost]
  26. public ActionResult Create(StudentModel smodel)
  27. {
  28. try
  29. {
  30. if (ModelState.IsValid)
  31. {
  32. StudentDBHandle sdb = new StudentDBHandle();
  33. if (sdb.AddStudent(smodel))
  34. {
  35. ViewBag.Message = "Student Details Added Successfully";
  36. ModelState.Clear();
  37. }
  38. }
  39. return View();
  40. }
  41. catch
  42. {
  43. return View();
  44. }
  45. }
  46.  
  47. // 3. ************* EDIT STUDENT DETAILS ******************
  48. // GET: Student/Edit/5
  49. public ActionResult Edit(int id)
  50. {
  51. StudentDBHandle sdb = new StudentDBHandle();
  52. return View(sdb.GetStudent().Find(smodel => smodel.Id == id));
  53. }
  54.  
  55. // POST: Student/Edit/5
  56. [HttpPost]
  57. public ActionResult Edit(int id, StudentModel smodel)
  58. {
  59. try
  60. {
  61. StudentDBHandle sdb = new StudentDBHandle();
  62. sdb.UpdateDetails(smodel);
  63. return RedirectToAction("Index");
  64. }
  65. catch
  66. {
  67. return View();
  68. }
  69. }
  70.  
  71. // 4. ************* DELETE STUDENT DETAILS ******************
  72. // GET: Student/Delete/5
  73. public ActionResult Delete(int id)
  74. {
  75. try
  76. {
  77. StudentDBHandle sdb = new StudentDBHandle();
  78. if (sdb.DeleteStudent(id))
  79. {
  80. ViewBag.AlertMsg = "Student Deleted Successfully";
  81. }
  82. return RedirectToAction("Index");
  83. }
  84. catch
  85. {
  86. return View();
  87. }
  88. }
  89. }
  90. }

 
8. Create Partial View from Action Method
1. Right Click on Index() Action Method and Select Add View. 2. Fill following details in Add View Dialog box.
  • a. View Name: Index
  • b. Template: List
  • c. Model Class: StudentModel (CRUDinMVC.Models)
  • d. Check both CheckBoxes
  • e. Click Add button to Add View.
3. View: Index()

Make sure to change the following highlighted line as an example.


  1. @model IEnumerable<CRUDinMVC.Models.StudentModel>
  2.  
  3. <p>
  4. @Html.ActionLink("Create New", "Create")
  5. </p>
  6. <table class="table">
  7. <tr>
  8. <th>
  9. @Html.DisplayNameFor(model => model.Name)
  10. </th>
  11. <th>
  12. @Html.DisplayNameFor(model => model.City)
  13. </th>
  14. <th>
  15. @Html.DisplayNameFor(model => model.Address)
  16. </th>
  17. <th></th>
  18. </tr>
  19.  
  20. @foreach (var item in Model) {
  21. <tr>
  22. <td>
  23. @Html.DisplayFor(modelItem => item.Name)
  24. </td>
  25. <td>
  26. @Html.DisplayFor(modelItem => item.City)
  27. </td>
  28. <td>
  29. @Html.DisplayFor(modelItem => item.Address)
  30. </td>
  31. <td>
  32. @Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
  33. @Html.ActionLink("Delete", "Delete", new { id=item.Id }, new { onclick = "return confirm('Are sure wants to delete?');" })
  34. </td>
  35. </tr>
  36. }
  37.  
  38. </table>


4. Follow same procedure for Create() and Edit() Method. Choose Create Template for Create() Method and Edit Template for Edit() Method.

View: Create()
  1. @model CRUDinMVC.Models.StudentModel
  2.  
  3.  
  4. @using (Html.BeginForm())
  5. {
  6. @Html.AntiForgeryToken()
  7. <div class="form-horizontal">
  8. <h4>StudentModel</h4>
  9. <hr />
  10. @Html.ValidationSummary(true, "", new { @class = "text-danger" })
  11. <div class="form-group">
  12. @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
  13. <div class="col-md-10">
  14. @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
  15. @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
  16. </div>
  17. </div>
  18.  
  19. <div class="form-group">
  20. @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })
  21. <div class="col-md-10">
  22. @Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } })
  23. @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })
  24. </div>
  25. </div>
  26.  
  27. <div class="form-group">
  28. @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })
  29. <div class="col-md-10">
  30. @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })
  31. @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })
  32. </div>
  33. </div>
  34.  
  35. <div class="form-group">
  36. <div class="col-md-offset-2 col-md-10">
  37. <input type="submit" value="Create" class="btn btn-default" />
  38. </div>
  39. </div>
  40. <h3>@ViewBag.Message</h3>
  41. </div>
  42. }
  43.  
  44. <div>
  45. @Html.ActionLink("Back to List", "Index")
  46. </div>
  47.  
  48. <script src="~/Scripts/jquery-1.10.2.min.js"></script>
  49. <script src="~/Scripts/jquery.validate.min.js"></script>
  50. <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>


View: Edit()
  1. @model CRUDinMVC.Models.StudentModel
  2.  
  3.  
  4. @using (Html.BeginForm())
  5. {
  6. @Html.AntiForgeryToken()
  7. <div class="form-horizontal">
  8. <h4>StudentModel</h4>
  9. <hr />
  10. @Html.ValidationSummary(true, "", new { @class = "text-danger" })
  11. @Html.HiddenFor(model => model.Id)
  12.  
  13. <div class="form-group">
  14. @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
  15. <div class="col-md-10">
  16. @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
  17. @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
  18. </div>
  19. </div>
  20.  
  21. <div class="form-group">
  22. @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })
  23. <div class="col-md-10">
  24. @Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } })
  25. @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })
  26. </div>
  27. </div>
  28.  
  29. <div class="form-group">
  30. @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })
  31. <div class="col-md-10">
  32. @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })
  33. @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })
  34. </div>
  35. </div>
  36.  
  37. <div class="form-group">
  38. <div class="col-md-offset-2 col-md-10">
  39. <input type="submit" value="Save" class="btn btn-default" />
  40. </div>
  41. </div>
  42. </div>
  43. }
  44.  
  45. <div>
  46. @Html.ActionLink("Back to List", "Index")
  47. </div>
  48.  
  49. <script src="~/Scripts/jquery-1.10.2.min.js"></script>
  50. <script src="~/Scripts/jquery.validate.min.js"></script>
  51. <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

5. Your Solution Explorer should look like this.
 
9. Configure RouteConfig.cs

1. Open RouteConfig.cs from Solution Explorer.
2. Change the highlighted code in your RouteConfig.cs file.
  1. using System.Web.Mvc;
  2. using System.Web.Routing;
  3.  
  4. namespace CRUDinMVC
  5. {
  6. public class RouteConfig
  7. {
  8. public static void RegisterRoutes(RouteCollection routes)
  9. {
  10. routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
  11.  
  12. routes.MapRoute(
  13. name: "Default",
  14. url: "{controller}/{action}/{id}",
  15. defaults: new { controller = "Student", action = "Index", id = UrlParameter.Optional }
  16. );
  17. }
  18. }
  19. }


 
10. Run Your Program

1. Open Index.cshtml View Page then press F5 to run your program. Selecting Index.cshtml will start your project with this page.

2. Index Page
3. Create Page.
4. Edit Page
5. Delete Page

Summary:

In this tutorial, I have tried to explain full and complete create, update and delete program in MVC 5 without entity framework. I have inserted a great number of screenshots so that you can easily finish this project on your system. Believe me, once after completing this chapter your understanding of MVC, will be increased at a great level.

Post a Comment

0 Comments