Question

I have an action method that accepts the following model - 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; } 
}

I also have a custom model binder to bind the POST data to the IEnumerable<LanguageItem>.

The question is how do I get DataAnnotations validation to work?

Was it helpful?

Solution

Very late answer I know, and it's for MVC3. Add the following to the end of your model binder BindModel method

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);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top