JoelFan
JoelFan

Reputation: 38704

Model binding on POST with query string AND form parameters

What is the defined behavior for form binding in ASP.NET/MVC if you POST a form and its action has query parameters and you have form data?

For example:

<form action="my/action?foo=1" method="post">
     <input type="hidden" name="bar" value="2">
</form>

If such a form is submitted should the controller get both foo and bar or only one of them?

Upvotes: 9

Views: 10334

Answers (3)

AaronLS
AaronLS

Reputation: 38367

Note, you can see this is supported by Html.BeginForm helper, you do so through routeValues:

@Html.BeginForm("ActionName", "ControllerName", new { foo = "1" })

It essentially generates the same html as your form tag, but wanted to post for those who find this question and want to know how to pass additional values that are not part of the form using the BeginForm helper.

Upvotes: 2

MattSavage
MattSavage

Reputation: 778

I think it should be able to get both. In this case, I would create a ViewModel that contains two string or int properties, one named 'foo' and the other named' bar' and have your ActionResult accept the ViewModel. You should see both values come in.

Upvotes: 0

carlosfigueira
carlosfigueira

Reputation: 87218

The controller will get both values. The default model binder will try to find matches for the parameters from both the URI (either query string or route parameters) or the body (and forms data is supported out-of-the-box).

Upvotes: 9

Related Questions