ProfK ProfK - 1 year ago 43
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

view with this Razor form:

@using (Html.BeginForm()) {

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

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

Then the controller for that view has this action:

[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(long id)

Where does this action get its
parameter value from? Is it somehow extracted from the only form value posted, the anti-forgery token
, 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)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download