2

我有一个接受以下模型的操作方法 - 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 验证工作?

4

1 回答 1

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);
    }
}
于 2012-09-29T22:06:17.687 回答