ProfK ProfK - 9 months ago 21
ASP.NET (C#) Question

How do Delete view and action get the model id?

In a standard MVC app, scaffolding controller with views gives a

Delete
view with this Razor form:

@using (Html.BeginForm()) {
@Html.AntiForgeryToken()

<div class="form-actions no-color">
<input type="submit" value="Delete" class="btn btn-default" /> |
@Html.ActionLink("Back to List", "Index")
</div>
}


Nowhere in the
Delete
view is any
id
field, hidden or not.

Then the controller for that view has this action:

[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(long id)
{
....
}


Where does this action get its
id
parameter value from? Is it somehow extracted from the only form value posted, the anti-forgery token
__RequestVerificationToken
, during some sort of model binding?

Answer Source

Because you have a GET method with a signature

public ActionResult Delete(long id)

and you using the default route (or at least a route definition containing /{id})

url: "{controller}/{action}/{id}"

When you navigate to that method, say using /yourController/Delete/10, the value of id is 10, and that is added to the action attribute of the <form> tag generated by your Html.BeginForm() method. When you submit the form, the value of the id parameter is bound for the route value in the forms action attribute (the DefaultModelBinder reads values from the form collection (any inputs you might have) as well as route values and query strings (among others)