我在ASP.NET MVC 2中使用自定义模型绑定器,如下所示:
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
if (controllerContext == null)
{
throw new ArgumentNullException("controllerContext");
}
if (bindingContext == null)
{
throw new ArgumentNullException("bindingContext");
}
BaseContentObject obj = (BaseContentObject)base.BindModel(controllerContext, bindingContext);
if(string.IsNullOrWhiteSpace(obj.Slug))
{
// creating new object
obj.Created = obj.Modified = DateTime.Now;
obj.ModifiedBy = obj.CreatedBy = controllerContext.HttpContext.User.Identity.Name;
// slug is not provided thru UI, derivate it from Title; property setter removes chars that are not allowed
obj.Slug = obj.Title;
ModelStateDictionary modelStateDictionary = bindingContext.ModelState;
modelStateDictionary.SetModelValue("Slug", new ValueProviderResult(obj.Slug, obj.Slug, …Run Code Online (Sandbox Code Playgroud) 我有一个实现的视图模型IValidatableObject包含一个字符串和另一个视图模型的集合,如下所示:
public sealed class MainViewModel
{
public string Name { get; set; }
public ICollection<OtherViewModel> Others { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我的验证Others使用以下提供的合同检查每个对象与不同的规则IValidatableObject:
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
foreach (var other in this.Others)
{
// validate or yield return new ValidationResult
}
}
Run Code Online (Sandbox Code Playgroud)
由于真实的复杂结构,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 …Run Code Online (Sandbox Code Playgroud)