Do you use TryUpdateModel instead of UpdateModel?
Rules to Better MVC|f6113a94-ea9d-4c29-9f67-4770573c432d
v2.0
Posted at
8/03/2013 5:20 AM by
Tiago Araujo
Rule Intro
UpdateModel will throw an exception if validation of the model fails. Instead of managing an exception, you should use TryUpdateModel as it adds the error to the ModelState dictionary. This lets you check the ModelState.IsValid property and decide how to handle the issue from there. This is an important distinction to be made because if we had used UpdateModel then our if (ModelState.IsValid) would not be hit in the event of a failure to bind.
Page Content
public ActionResult Create()
{
Entity myEntity = new Entity();
UpdateModel(myEntity);
}
- Figure: Bad Example – UpdateModel may throw an exception and the ModelState dictionary won’t be updated
public ActionResult Create()
{
Entity myEntity = new Entity();
TryUpdateModel(myEntity);
if (ModelState.IsValid)
{
// ...
}
}
- Figure: Good Example – TryUpdateModel will gracefully handle validation and will add to the ModelState dictionary so we can check for validity
{74FBD7D4-7391-494D-B855-44426F7170EB}
Do you feel this rule needs an update?