MVC2 TryUpdateModel's include attributes not ignoring validations on fields unincluded
I have a form in my MVC 2 application that allows a user to update a set of fields from a model object, this is purely an update as the model object is already existing with its required fields entered. However when I try to update a small set of fields and call TryUpdateModel
on my model object it fails and my modelstate has errors based on required fields that have already been filled out.
Here is my controller code:
[HttpPost]
public ActionResult Work(int id, FormCollection forms)
{
var lead = claimRepo.GetLeadByID(id);
if (lead == null)
return View("NotFound");
if (TryUpdateModel(lead, "Lead")) {...}
}
I've even tried explicitly stating which fields to update like so
TryUpdateModel(lead, "Lead", new string[] { "Date", "UserID", ...}) {...}
And it still fails, is there some reason this doesn't ignore validation on fields not included or am I doing something wrong?
Thanks!
EDIT
I found the issue, I had a property on my class that wasn't database backed and was marked as required in metadata, so addin开发者_如何学Gog a getter and setter to return what the property represented caused the TryUpdateModel
to pass, but I am still curious as to why the explicit include of properties didn't ignore the field I hadn't included.
Another Edit
I have a user model as well with all database backed required fields and trying to explicitly state which fields are being updated still results in modelstate errors on the fields missing in the form, but are filled in on the model object from the db that is being updated.
I am not sure when the default behaviour was changed for validating only incoming data, from what I know I think only asp.net mvc1 supported it, then it changed in asp.net mvc2 anyway you could say [Validate(false)] and allow the partial data to go through and manually do some validation. You could use a ViewModel and validate all fields on the view model if needed as a second option. A helpful link: partial validation
精彩评论