ASP.NET MVC Delete View -how does this work

14,489

Solution 1

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

Solution 2

MVC is heavily "convention based".

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

 public ActionResult Delete(int addressID)
Share:
14,489

Related videos on Youtube

tom
Author by

tom

Updated on September 16, 2022

Comments

  • tom
    tom over 1 year

    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?