Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TryUpdateModel vs. strongly typed method parameter

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?

like image 548
spaceagestereo Avatar asked Oct 09 '22 20:10

spaceagestereo


2 Answers

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.

like image 80
Josh Avatar answered Oct 12 '22 10:10

Josh


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.

like image 42
Adam Tuliper Avatar answered Oct 12 '22 09:10

Adam Tuliper