goorj
goorj

Reputation: 443

POSTing to controller, how to get id from URL

If I POST a form to a target URL which includes an ID, e.g.

/mycontroller/createItemAndAddTo/5

How can I get to the Id (=5) in the [HttpPost] ActionResult subroutine (which takes the model as parameter)

I'd like to leave out the Id from the POST data/form, and get it from the URL as it is already present there

In this case the Id is a foreign key, and I would normally include it as a hidden field, but it seems unnecessary as it is included already

Upvotes: 3

Views: 3740

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

If you have a standard route setup which has the id as last token of the url then the default model binder will populate its value automatically:

[HttpPost]
public ActionResult Foo(int id)
{
    // id = 5 here
}

or if your view model has an Id property:

[HttpPost]
public ActionResult Foo(MyViewModel model)
{
    // model.Id = 5 here
}

Upvotes: 7

Related Questions