简体   繁体   中英

Validation Application Block - How to use validation metada class

I'm using VAB to validate some classes with attributes and I'm using a metadata class to share the same validation among different classes. When i try to validate an object in the controller (btw i'm using asp.net mvc) the ValidationResults does not have errors and my entity should not be valid. But, ASP.NET MVC does his magic because ModelState.IsValid is false. I guess the problem is the way I'm doing the manual validations.

In Global.asax I'm loading the associations between the classes and metadata classes.

Global.ASAX

private static void RegisterMetadataExtensions()
{
    AssociatedMetadataTypeTypeDescriptionProvider typeDescriptionProvider;

    typeDescriptionProvider =
        new AssociatedMetadataTypeTypeDescriptionProvider(
            typeof(FooViewModel), typeof(FooMetadata));

    TypeDescriptor.AddProviderTransparent(typeDescriptionProvider,
        typeof(FooViewModel));

    typeDescriptionProvider =
        new AssociatedMetadataTypeTypeDescriptionProvider(
            typeof(FooCommand), typeof(FooMetadata));

    TypeDescriptor.AddProviderTransparent(
        typeDescriptionProvider, typeof(FooCommand));
}

Controller

[HttpPost]        
public ActionResult Action(FooViewModel vm)
{
    Validator<FooViewModel> validator =
        ValidationFactory.CreateValidator<FooViewModel>();

    ValidationResults res = validator.Validate(vm);

    //res.Count is 0

OR

    ValidationResults res = Validation.Validate<FooViewModel>(vm);

    //res.Count is 0

    //ModelState.IsValid is false
    if(ModelState.IsValid)

Any idea is welcome.

Thanks in advanced.

I'm a big fan of the enterprise library, but I think a better way to do validation with MVC is to make your ViewModel implement IValidatableObject . That way, it automatically gets validated during the binding phase that sets ModelState.Isvalid

为了使您的VAB验证程序能够参与ASP.NET MVC的验证,我认为您需要实现ModelValidatorProvider并包装VAB验证结果,如下所述... http://bradwilson.typepad.com/blog/2009/10/enterprise- library-validation-example-for-aspnet-mvc-2.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM