Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC Delete View -how does this work

This is a simple question with simple code, I just wanted to be verbose to make sure I'm understood.

Standard generated views for an ASP.NET MVC application will have a delete view which ends like the below -

@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    <p>
        <input type="submit" value="Delete" /> |
        @Html.ActionLink("Back to List", "Index")
    </p>
}

The controller methods are standard -

  public ActionResult Delete(int addressID)
    {
        Address address = db.Address.Find(addressID);
        if (address == null)
        {
            return HttpNotFound();
        }
        return View(address);
    }

    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(int addressID)
    {
        Address address = db.Address.Find(addressID);
        db.Address.Remove(address);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

The HTML this produces looks like -

<form action="/Address/Delete?AddressID=2" method="post">    
<input name="__RequestVerificationToken" type="hidden" value="...snip..." />    <p>
        <input type="submit" value="Delete" /> |
        <a href="/Address">Back to List</a>
    </p>
</form>

As you can see the AddressID is included in the form action, but I didn't "do" anything to put it there. I just sent pack the model.

How does the AddressID get into the form action?

like image 647
tom Avatar asked Mar 22 '23 04:03

tom


2 Answers

This is due to automatic mapping and asp.net routing resulting from your method signatures.

public ActionResult Delete(int addressID)
public ActionResult DeleteConfirmed(int addressID)

For details, see the Automatically Mapping Action-Method Parameters section of Controllers and Action Methods in ASP.NET MVC Applications and details on routing ASP.NET Routing

like image 170
Jenn Avatar answered Mar 24 '23 18:03

Jenn


MVC is heavily "convention based".

You did provide the necessary information, both Delete Actions have the same id parameter:

 public ActionResult Delete(int addressID)
like image 24
Henk Holterman Avatar answered Mar 24 '23 16:03

Henk Holterman