Monday, January 3, 2011

TryUpdateModel vs Model.IsValid

I am intensively working in asp.net mvc since last September and below is my findings about TryUpdateModel and Model.IsValid.

TryUpdateModel
This method can be used to bind the view to model when we didn't pass the model as parameter to action method. This has multiple overloads that will help to set only specific object if multiple subobjects found in the model, exclude some properties and so on. For your info, this method's last line returns the Model.IsValid.

Public ActionResult Update(string id)
{
//getting the object from the db
object obj = GetObjectById(id);
//binding the view to the model and validating the model
If(TryUpdateModel(obj))
{
UpdateObject(obj);
RedirectToAction("Index");
}
return View(obj);
}

Model.IsValid

This can be used to validate the model when we pass the model as a parameter. When we pass the model as a parameter the model binding is happening automatically and validation status is set to IsValid.

Public ActionResult Update(object obj)
{
//binding the view to the model and validating the model
If(Model.IsValid)
{
UpdateObject(obj);
RedirectToAction("Index");
}
return View(obj);
}

No comments:

Post a Comment