DataAnnotations验证和自定义模型绑定器

时间:2010-05-31 10:47:30

标签: asp.net-mvc-2 data-annotations custom-model-binder

我有一个接受以下模型的动作方法 - LanguagesViewModel:

public class LanguagesViewModel : ViewModelBase
{
 IEnumerable<LanguageItem> Languages { get; set; }
}

public class LanguageItem
{
 [Required]
 public int LanguageId { get; set; }

 [Required]
 public int SpeakingSkillId { get; set; }

 [Required]
 public int WritingSkillId { get; set; }

 [Required]
 public int UnderstandingSkillId { get; set; } 
}

我还有一个自定义模型绑定器,用于将POST数据绑定到IEnumerable<LanguageItem>

问题是如何让DataAnnotations验证工作?

1 个答案:

答案 0 :(得分:5)

我知道的答案非常晚,而且它适用于MVC3。将以下内容添加到模型绑定器BindModel方法的末尾

if (model != null)
{
    System.Web.Mvc.ModelMetadata modelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType());
    ModelValidator compositeValidator = ModelValidator.GetModelValidator(modelMetadata, controllerContext);
    foreach (ModelValidationResult result in compositeValidator.Validate(null))
    {                                    
        bindingContext.ModelState.AddModelError(result.MemberName, result.Message);
    }
}