In MVC2 I used to create strongly typed views in a way that when I posted, I never used the FormCollection object. My signatures always looked like so:
[AcceptVerbs(HttpVers.Post)]
public Create(Person newPerson)
{
//code to update the person from the post
}
But now I'm seeing this new TryUpdateModel way where I would just write something like:
[AcceptVerbs(HttpVers.Post)]
public Create()
{
Person thePersonToCreate = new Person()
TryUpdateModel(thePersonToCreate)
{
//Code to create the person if model is valid
}
}
So now it seems I have to mock up the HTTPContext in order to test this method. However, it seems like I can still use the former way using strongly typed methods. I realize that the TryUpdateModel method is an improvement for those who would use the FormCollection method of doing things but why bother with TryUpdateModel?
There are instances where this is desirable. A good example is when your model requires a more complex initialization, or factory method to create.
[AcceptVerbs(HttpVers.Post)]
public Create()
{
var dataAccess = new MyDataAccess("Another Param");
Person thePersonToCreate = new Person(dataAccess);
TryUpdateModel(thePersonToCreate)
{
//Code to create the person if model is valid
}
}
Now one might argue that a custom ModelBinder is a better solution here, but that might be more effort than it is worth if this is a one off situation. Also, hiding this detail in a ModelBinder makes errors more difficult to debug.
There are other situations I'm sure, but this is just a quick example.
Some also use that method when you have to load information into an entity first and merge your values for validation purposes. You could however just use automapper in these cases but some companies prohibit open source code.
I would argue almost no one uses FormCollection in a well architected app.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With