我有一个实现的视图模型IValidatableObject
包含一个字符串和另一个视图模型的集合,如下所示:
public sealed class MainViewModel
{
public string Name { get; set; }
public ICollection<OtherViewModel> Others { get; set; }
}
我的验证检查每个对象Others
使用提供的合同反对不同的规则IValidatableObject
:
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
foreach (var other in this.Others)
{
// validate or yield return new ValidationResult
}
}
由于实际结构复杂MainViewModel
我必须创建一个自定义模型绑定器,它重新构建模型并将 POST 数据分配给相关组件。我遇到的问题是,没有任何内容得到验证,导致上下文级别的验证错误,因为它违反了某些数据库约束,而且我不确定我做错了什么 - 我假设ModelState.IsValid
会调用Validate
方法在我的视图模型上,但它似乎并没有那样走下去。
我的模型活页夹看起来像这样:
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
int modelId = (int)controllerContext.RouteData.Values["id"];
// query the database and re-build the components of the view model
// iterate the POST data and assign to the model where necessary
// should I be calling something here to validate the model before it's passed to the controller?
return model;
}
任何帮助表示赞赏!
Validator.TryValidateObject
好吧,看来我更接近了。我现在可以得到我的IValidatableObject
通过将以下内容添加到我的自定义模型绑定器来运行的方法:
var validationResults = new HashSet<ValidationResult>();
var isValid = Validator.TryValidateObject(model, new ValidationContext(model, null, null), validationResults, true);
看来Validator.TryValidateObject
调用验证方法并将最后一个参数设置为true
使其验证所有属性。但是,我现在坚持要获得validationResults
到控制器,以便可以以有意义的方式使用它们。