views:

37

answers:

1

I have a controller with an action that has 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?

+2  A: 

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.

Darin Dimitrov
In my case, I had a view model with a parameter that was named the same as an action parameter. I forgot to set the view model value in my controller and was quite surprised to see the correct value in the view. It was obviously pulling the value from the action parameter.To me, this all seems a bit counter productive based on the gotcha that you pointed out. View fields mapping back to an action seems to make total sense to me. Action parameters mapping to views and overriding strongly typed view models, this seems wrong. Can you point out a valid reason for doing this?Thanks,
Andrew Robinson