ActionLink Delete Confirmation

Subby picture Subby · Sep 18, 2012 · Viewed 7.8k times · Source

I want to make a Javascript popup asking if I want to delete a listing.

Here is what I have at the moment (Doesn't work - Guid is null when catched by the Controller).

@Html.ActionLink("Delete", "Delete", "Listing", listing.Guid, new { onclick = "return confirm('Are you sure you want to delete this listing?')" })

The first Delete is the string, the second Delete is the ActionName of the method, Listing is the Controller name, listing.Guid is the parameter which I want to send across and lastly, of course, the onclick is the Javascript.

Any idea where I may be going horribly wrong?

Edit Also, any idea how I can have a more pretty confirmation dialog box? Using Bootstrap.

Answer

Darin Dimitrov picture Darin Dimitrov · Sep 18, 2012

You could use an anonymous object to pass route values:

@Html.ActionLink(
    "Delete", 
    "Delete", 
    "Listing", 
    new { id = listing.Guid }, 
    new { onclick = "return confirm('Are you sure you want to delete this listing?')" }
)

and the respective controller action:

public ActionResult Delete(Guid id)
{
    ...
}

And yes, it's a very bad idea to use ActionLinks and GET requests to invoke actions that are modifying state on the server (such as deleting something). A much better approach is to use the correct HTTP verb for this case - DELETE. But since HTML forms do not universally support this verb you could either use AJAX or use POST verb:

@using (Html.BeginForm("Delete", "Listing", new { id = listing.Guid }, FormMethod.Post, new { onsubmit = "return confirm('Are you sure you want to delete this listing?');" }))
{
    @Html.HttpMethodOverride(HttpVerbs.Delete)
    <button type="submit">Delete</button>
}

and your respective controller action:

[HttpDelete]
public ActionResult Delete(Guid id)
{
    ...
}