Model binding on POST with query string AND form p

2019-04-22 05:38发布

问题:

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?

回答1:

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).



回答2:

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.



回答3:

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.