asp.net mvc tryupdate failing on custom viewmodel
I have a viewmodel which is returned from a insert call on a MVC page.
It exposes properties according to the underlying model as well as some calculated properties.
Everything is fine except when I run an if (tryupdateModel(viewModel))
. At which point it seems the calculated properties cause an error and it wont pass the if statement?
Is there an annotation I can put on this property to prevent it being 开发者_如何学Pythonchecked in the tryupdate
?
or how do i determine exactly what it is thats not allowing this to return true?
Is there an annotation I can put on this property to prevent it being checked in the tryupdate?
One way to prohibit updating a particular property is to use:
TryUpdateModel(model, null, null, new [] {"SecretProperty"}); // Blacklist
TryUpdateModel(model, new [] {"Prop1", "Prop2", "etc"}); // Whitelist - recommended
The other is to implement custom ModelBinder that reflects on the properties and ignores ones that should not be updated:
public class ApplicationModelBinder : DefaultModelBinder {
protected override PropertyDescriptorCollection GetModelProperties(ControllerContext controllerContext, ModelBindingContext bindingContext) {
var allProps = GetTypeDescriptor(controllerContext, bindingContext).GetProperties();
var resulting = new PropertyDescriptorCollection(null);
//Filter out the props with no scaffolding set
foreach(PropertyDescriptor prop in allProps) {
if (ShouldIncludeProperty(bindingContext, prop))
resulting.Add(prop);
}
return resulting;
}
private static bool ShouldIncludeProperty(ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor) {
var doNotScaffold = propertyDescriptor.Attributes.OfType<ScaffoldColumnAttribute>().Any(x => !x.Scaffold);
return !doNotScaffold;
}
}
Then you can apply [ScaffoldColumn(false)]
to the property that is not updateable.
I use this approach.
how do i determine exactly what it is thats not allowing this to return true?
After the call to TryUpdateModel
you can inspect ModelState
property of the controller and find where the errors are.
This will depend on how you are performing validation. If you are using data annotations you need to remove any attributes on the calculated properties. You also need to check which property is failing validation. You may execute the following command after TryUpdateModel:
var errors = ModelState
.Where(x => x.Value.Errors.Count > 0)
.Select(x => new { x.Key, x.Value.Errors })
.ToArray();
This will give you the list of errors and their corresponding properties and might help you understand what is happening and why validation is failing.
精彩评论