Introduction
In this post, How to implement Basic CRUD Functionality with the Entity Framework and ASP.NET MVC application.Part 3 : Perform delete functionality of CRUD Operation.
I have split the entire application split into following 3 parts for making things more simple and understandable especially for beginners.
- Part 1 : Perform read functionality of CRUD Operation.
- Part 2 : Perform create and update functionality of CRUD Operation.
- Part 3 : Perform delete functionality of CRUD Operation.
Steps :
Step-1: Add an action into your controller for get view for Delete contact.
Here I have used "Delete" Action. Please write this following code[HttpGet] public ActionResult Delete(int id) { var c = GetContact(id); if (c == null) { return HttpNotFound(); } return View(c); }
Step-2: Add view for the Action & design.
Right Click on Action Method (here right click on the action) > Add View... > Enter View Name > Select View Engine (Razor) > Check "Create a strong-typed view" > Scaffold template (Delete) > Select your model class > Add.[N:B:Please Rebuild solution before add view.]
@model MVCCRUD.Contact @{ ViewBag.Title = "Delete"; } <h2>Delete</h2> <h3>Are you sure you want to delete this?</h3> <fieldset> <legend>Contact</legend> <div class="display-label"> @Html.DisplayNameFor(model => model.ContactPerson) </div> <div class="display-field"> @Html.DisplayFor(model => model.ContactPerson) </div> <div class="display-label"> @Html.DisplayNameFor(model => model.ContactNo) </div> <div class="display-field"> @Html.DisplayFor(model => model.ContactNo) </div> <div class="display-label"> @Html.DisplayNameFor(model => model.CountryID) </div> <div class="display-field"> @Html.DisplayFor(model => model.CountryName) </div> <div class="display-label"> @Html.DisplayNameFor(model => model.StateID) </div> <div class="display-field"> @Html.DisplayFor(model => model.StateName) </div> </fieldset> @using (Html.BeginForm()) { <p> @Html.AntiForgeryToken() <input type="submit" value="Delete" /> | @Html.ActionLink("Back to List", "Index") </p> }
Step-3: Add an another action for POST method for Delete contact to the database.
Please write this following code[HttpPost] [ValidateAntiForgeryToken] [ActionName("Delete")] public ActionResult DeleteContact(int id) { using (MyDatabaseEntities dc = new MyDatabaseEntities()) { var v = dc.Contacts.Where(a => a.ContactID.Equals(id)).FirstOrDefault(); if (v != null) { dc.Contacts.Remove(v); dc.SaveChanges(); return RedirectToAction("Index"); } else { return HttpNotFound(); } } }
Step-4: Run Application.
- Part 1 - How to Basic CRUD operations using Jquery ajax and modal popup in ASP.NET MVC4.
- Part 1 - How to implement Basic CRUD Functionality with the Entity Framework and ASP.NET Webforms application