Perform CRUD Functionality in ASP.Net MVC 5

Introduction

In this article we'll learn how to do Create, Read, Update and Delete (CRUD) operations with the Entity Framework Data Model in the ASP.NET Web Application based on the MVC Project Template in Visual Studio 2013. As I described in the MVC with Entity Framework Data Model, we can create a MVC Application with Entity Framework 6, therefore here we perform the CRUD functionality.

So, let's proceed with the following section:

  • Updating the application and Perform CRUD Operations

Updating the application and doing CRUD Operations

At first we update our application to designate more briefly. We can also modify our pages to define more details of students about their enrollments and courses in their details. Use the following procedure to update the details page.

Editing Details Page

As we define the enrollments property in the student that holds the collection, so here we define it in the details page so that we can show which courses the student enrolls in.

Step 1: You can the Details Action in the Controllers\StudentController.cs page that it used in the Find() to get the student entity.

  1. public ActionResult Details(int? id)  
  2. {  
  3.     if (id == null)  
  4.     {  
  5.         return new HttpStatusCodeResult(HttpStatusCode.BadRequest);  
  6.     }  
  7.     Student student = db.Students.Find(id);  
  8.     if (student == null)  
  9.     {  
  10.         return HttpNotFound();  
  11.     }  
  12.     return View(student);  
  13. } 

Step 2: Open the Views\Student\Details.cshtml page and add the highlighted code below:

  1. <dd>  
  2.     @Html.DisplayFor(model => model.EnrollmentDate)  
  3. </dd>  
  4. <dt>  
  5.     @Html.DisplayNameFor(model => model.Enrollments)  
  6. </dt>  
  7. <dd>  
  8.     <table class="table">  
  9.         <tr>  
  10.             <th>Course Name</th>  
  11.             <th>Grade</th>  
  12.         </tr>  
  13.         @foreach (var items in Model.Enrollments)  
  14.         {  
  15.             <tr>  
  16.                 <td>  
  17.                     @Html.DisplayFor(modelitems => items.Course.Name)  
  18.                 </td>  
  19.                 <td>  
  20.                     @Html.DisplayFor(mdoelitems => items.Grade)  
  21.                 </td>  
  22.             </tr>  
  23.         }  
  24.     </table>  
  25. </dd> 

You can press "Ctrl+K+D" to apply the indentation in your code. In the code above the Enrollments navigation property is used to display the Course name and Grade of the student, if the student enrolls in one or more courses then it is displayed again by the foreach loop. All of this data is retrieved from the database automatically when it is needed.

Step 3: Press "Ctrl+F5" to run the application.

Step 4: Click on the "Students" link and then we want the details of Nimit. So, click on the details link:

Details Page in MVC

In the preceding screenshot, you can see that the student enrollments in various courses and grade. It shows the list of enrollments for the selected student.

Editing Create Page

Step 1: Open the Controllers\StudentController.cs page and find the Create Action and modify it with the highlighted code below:

  1. [HttpPost]  
  2. [ValidateAntiForgeryToken]  
  3. public ActionResult Create([Bind(Include="FirstName,LastName,EnrollmentDate")] Student student)  
  4. {  
  5.     try  
  6.     {  
  7.         if (ModelState.IsValid)  
  8.         {  
  9.             db.Students.Add(student);  
  10.             db.SaveChanges();  
  11.             return RedirectToAction("Index");  
  12.         }  
  13.     }  
  14.     catch (DataException /*dataex*/)  
  15.     {  
  16.         ModelState.AddModelError("","Unable to save changes. Try again or Contact to the Administrator");  
  17.     }  
  18.     return View(student);  
  19. } 

The code above will add the Student entity in the Student entity set that is created by the MVC model binder and save the changes. We remove the ID because it is the primary key column and when the new row is inserted, SQL Server will set this automatically. The user cannot set the ID value from Input.

Step 2: Run the application and click on "Create new link".

Create New in MVC

Step 3: In Create New page we can show the server-side validation by entering the wrong date as shown below:

Validation in MVC

You can see the Server-Side validation (by-default) in the code below:

  1. if (ModelState.IsValid)  
  2. {  
  3.     db.Students.Add(student);  
  4.     db.SaveChanges();  
  5.     return RedirectToAction("Index");  
  6. } 

Step 4: Enter the valid date and you can see the added record as in the following:

New Record Created in MVC

Editing Edit Page

We add the "try-catch" block here to update the Edit page. It is optional. It uses the Find() to get the Student entity.

Step 1: Modify your code with the highlighted code below:

  1. [HttpPost]  
  2. [ValidateAntiForgeryToken]  
  3. public ActionResult Edit([Bind(Include="ID,FirstName,LastName,EnrollmentDate")] Student student)  
  4. {  
  5.     try  
  6.     {  
  7.         if (ModelState.IsValid)  
  8.         {  
  9.             db.Entry(student).State = EntityState.Modified;  
  10.             db.SaveChanges();  
  11.             return RedirectToAction("Index");  
  12.         }  
  13.     }  
  14.     catch(DataException /*DataEx*/)  
  15.     {  
  16.         ModelState.AddModelError("""Unable to save changes. Try again or Contact to the Administrator");  
  17.     }  
  18.     return View(student);  
  19. } 

The code above sets a flag on the entity and indicates that this has been changed. When the flag has been changed the SaveChanges() runs and the modified flag is responsible for informing the Entity Framework to run the update query in the SQL statement and update the row.

Step 2: Press "Ctrl+F5" to run the application and click on the "Edit" link to edit the student.

Edit Page in MVC

Step 3: You can see the Edited record in the following:

Edited Record in MVC

Editing Delete Page

The Delete method in the StudentController.cs page uses the Find() to delete the row as we saw above in the "Details" and "Create" pages. We can add some custom error message if the SaveChanges() failed to execute.

There are two types of action methods called in here. When the method calls and the response is GET, it shows the confirmation page to delete the selected data and when the user accepts it, a POST request is created. The HttpPost Delete method is called and then delete operation is actually performed.

We'll add a "try-catch" block here to show the custom message if any error occur during the update of the database.

Step 1: Find and replace the Delete action method, with the highlighted code below:

  1. public ActionResult Delete(int? id, bool? ErrorinSaveChanges=false)  
  2. {  
  3.     if (id == null)  
  4.     {  
  5.         return new HttpStatusCodeResult(HttpStatusCode.BadRequest);  
  6.     }  
  7.     if (ErrorinSaveChanges.GetValueOrDefault())  
  8.     {  
  9.         ViewBag.ErrorMessage = "Failed to Delete. Try again or Contact to System Administrator";  
  10.     }  
  11.     Student student = db.Students.Find(id);  
  12.     if (student == null)  
  13.     {  
  14.         return HttpNotFound();  
  15.     }  
  16.     return View(student);  
  17. } 

Step 2: Modify the HttpPost DeleteConfirmed action method with the code below:

  1. [HttpPost]  
  2. [ValidateAntiForgeryToken]  
  3. public ActionResult Delete(int id)  
  4. {  
  5.     try  
  6.     {  
  7.         Student student = db.Students.Find(id);  
  8.         db.Students.Remove(student);  
  9.         db.SaveChanges();  
  10.     }  
  11.     catch (DataException /*DataEx*/)  
  12.     {  
  13.         return RedirectToAction("Delete"new { id = id, errorinsavechanges = true});  
  14.     }  
  15.         return RedirectToAction("Index");  
  16. } 

The code above gets the selected entity and calls Remove() to change the status to "Delete". Now the SQL DELETE  command executes, when the SaveChanges() method runs.

Step 3: Open the Views\Student\Delete.cshtml page and modify it with the highlighted code below:

  1. <h2>Delete</h2>  
  2. <p class="error">@ViewBag.ErrorMessage</p>  
  3. <h3>Are you sure you want to delete this?</h3> 

Step 4: Run the application and open "Students" link. Click on the "Delete" link to delete the data.

Delete Page in MVC

Step 5: When on the confirmation page and you click on Delete, the data is deleted and the Index page is displayed.

Summary

This article has explained how to do CRUD operations in ASP.NET MVC Applications. You can also update and generate the elements. Now, in the article, we'll perform the paging and sorting techniques. Thanks for reading.


Similar Articles