Do controller action parameters automatically map to view input tags?
I have a controller with an action that ha开发者_如何学Pythons a parameter (JobID). I was surprised to see that it automatically mapped to a hidden field with the same name in the view that the controller returned. I am using strongly typed view models and assumed I needed to pass all model properties as part of the view model. It appears that this is not the case.
I know view fields map back to action parameters on invoked controllers but didn't realize this worked both ways. Am I understanding this correctly? Any gotchas with this?
If you use HTML helpers to generate those input tags then when rendering they will first look at the request parameters (POST and GET) and then the model and ViewData. The condition for this is to have an action parameter with the same name.
The gotcha is that you cannot modify the value inside your controller action and it will always use the one passed as parameter. So consider for example the following POST action:
[HttpPost]
public ActionResult Index(Job job)
{
job.JobID = 10;
return View();
}
which is posted to with jobID = 5
. Even if you set the value to 10
the html helper will use 5
when rendering.
精彩评论