Monday, July 11, 2011

MVC3 TryUpdateModel() -Update Model for Edit

When we want to update model with edited values we can use TryUpdateModel() method.

example
[Httppost]
public ActionResult edit(int id)
{
    var user= UserRepository.GetUser(id);

    if (TryUpdateModel(user))
    {
        UserRepository.save();
    }

    return view()
}


But some times when we use TryUpdateModel() the model does not update that mean the method return false.So in that case we need to find out the error so we can do that as flowing it will return the list of errors and their corresponding properties.

[Httppost]
public ActionResult edit(int id)
{
    var user= UserRepository.GetUser(id);

    if (TryUpdateModel(user))
    {
        UserRepository.save();
    }
else{
//the tru update method return false
    
    var errors = ModelState
    .Where(m => m.Value.Errors.Count > 0)
    .Select(m => new { m.Key, m.Value.Errors })
    .ToArray();

}

    return view()
}

Why TryUpdateModel() return false ?

Most of the time the TryUpdateModel() method return false when we have not add editable field or hidden filed for all the required fields to view page.
so we can simply add hidden filed to the view which we don't need to change during the update method.

so My user Model
Public Class User{
[Requried]
public int UserId{get;set}
[Requried]
public string UserName {get;set}
[Requried]
pubic string UserCode{get;set}

pubic string Description{get;set}

public string Address{get;set}

}

So if  I want to update UserDescription in my edit page
I have to put UserId,UserName and UserCode as Hidden filed

But if our model content large number of fields and we only need to update few of fields in that case we can do it by specify the fields which we need to update as following

TryUpdateModel(model, new [] {"Description", "Address"}); // In this case the TryUpdate() only  check vaidation "Description","Address"




And also we can do it as fallowing by mentioning the field which should not update
TryUpdateModel(model, null, null, new [] {"UserId","UserName ","UserCode"});//In this case the TryUpdate() ignore "UserId","UserName" and "Usercode" vaidation

No comments:

Post a Comment