Here is my approach for deleting stuff with ASP.NET MVC 2.
As mentioned here, the default Delete view isn't quite correct. What I wanted is a deletion solution that:
- is powered with Ajax for a better user experience
- we will make a HTTP DELETE on /Items/Delete/12 to delete item #12
- is accessible for non-JS enabled browsers (we need a confirmation form)
- when confirmed, the deletion occurs with HTTP POST on /Items/Delete/12 to delete item #12
With those specifications, we can write the following (wrong) controller code:
public class ItemsController : Controller { [HttpGet] public ActionResult Delete(int id) { ViewData.Model = new ConfirmFormModel { Id = id.ToString(), BackAction = "Index" }; return View(); } [HttpDelete] [HttpPost] public ActionResult Delete(ConfirmFormModel model) { ViewData.Model = model; // business action here // if we use Ajax, backaction will be null and have // to prevent a secondary GET request return model.BackAction == null ? null : RedirectToAction(model.BackAction); } }
/// <summary> /// Simple model class to store the Id for a confirmation form. /// </summary> public class ConfirmFormModel { /// <summary> /// Item's ID /// </summary> public string Id { get; set; } /// <summary> /// Confirmation message. /// </summary> public string Message { get; set; } /// <summary> /// The controller action to redirect to if the user wants to cancel. /// </summary> public string BackAction { get; set; } }
A created a little model class to store the confirmation message and the item ID; this way I can use it all over my project. You can notice the [HttpDelete] and [HttpPost] on the second Delete() method. Obviously this won't work as asked here. You have to create your own attribute.
So I created the related views with (not-included) javascript. Here is the index:
<!-- Index page --> <ul> <% for (int i = 0; i < 10; i++) { %> <li><%= Html.ActionLink("Delete #" + i, "Delete", new { id = i }, new { @class = "deleteLink" })%></li> <% } %> </ul>
The delete page where I include a generic partial-view:
<!-- Delete page --> <h3>Confirmation</h3> <% Html.RenderPartial("ConfirmForm", Model); %>
Finally, the partial view:
<!-- Delete form in a partial view --> <% Html.BeginForm(); %> <fieldset> <legend>Confirmation</legend> <p><%= Html.Encode(Model.Message ?? "Are you sure you want to delete this?")%></p> <p> <%= Html.HiddenFor(m => m.Id) %> <%= Html.HiddenFor(m => m.BackAction) %> <%= Html.ActionLink("Cancel", Model.BackAction ?? "Index") %> <input type="submit" name="Continue" value="Continue" /> </p> </fieldset> <% Html.EndForm(); %>
Now we have a working solution to confirm some action on a website. Sources attached...












