加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – MVC 2 vs MVC 3自定义验证属性使用DataAnnotatio

发布时间:2020-12-15 23:13:46 所属栏目:asp.Net 来源:网络整理
导读:我读了一些帖子,但现在不能发现,在MVC 3中,创建验证器并不是真正需要的,只是属性.这是真的?我说我觉得这个属性有它的IClientValidatable,令人困惑.那么如果注释具有客户端脚本名称(IClientValidatable)和验证(ValidationAttribute IsValid)的能力,DataAnnot
我读了一些帖子,但现在不能发现,在MVC 3中,创建验证器并不是真正需要的,只是属性.这是真的?我说我觉得这个属性有它的IClientValidatable,令人困惑.那么如果注释具有客户端脚本名称(IClientValidatable)和验证(ValidationAttribute IsValid)的能力,DataAnnotationsModelValidator类将执行什么操作?

如果我没有在全局中注册与验证器的属性,这将是非常好的.这可以做吗我读了一些不好的建议吗?

编辑:有趣的是,我只是通过排除验证器来测试它,将所有的逻辑放在IsValid中,并且它的效果很好.我猜,唯一可能会丢失的是控制器上下文,但我不确定这在验证中是有用的.如果需要服务,IsValid有ValidationContext,它具有ServiceContainer.任何真正的劣势,我不会在这里拿起来?

编辑2:
我将从这个例子开始一个验证器:http://blogs.msdn.com/b/simonince/archive/2010/06/04/conditional-validation-in-mvc.aspx

属性:

public class RequiredIfAttribute : ValidationAttribute,IClientValidatable
{
    private RequiredAttribute innerAttribute = new RequiredAttribute();
    public string DependentProperty { get; set; }
    public object TargetValue { get; set; }

    public RequiredIfAttribute(string dependentProperty,object targetValue)
    {
        this.DependentProperty = dependentProperty;
        this.TargetValue = targetValue;
    }

    public override bool IsValid(object value)
    {
        return innerAttribute.IsValid(value);
    }

    public System.Collections.Generic.IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata,ControllerContext context)
    {
        ModelClientValidationRule modelClientValidationRule = new ModelClientValidationRule()
        {
            ErrorMessage = FormatErrorMessage(metadata.DisplayName),ValidationType = "requiredifattribute"
        };
        modelClientValidationRule.ValidationParameters.Add("requiredifattribute",DependentProperty);
        yield return modelClientValidationRule;
    }
}

验证者:

public class RequiredIfValidator : DataAnnotationsModelValidator<RequiredIfAttribute>
{
    public RequiredIfValidator(ModelMetadata metadata,ControllerContext context,RequiredIfAttribute attribute)
        : base(metadata,context,attribute)
    {
    }

    public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
    {
        return base.GetClientValidationRules();
    }

    public override IEnumerable<ModelValidationResult> Validate(object container)
    {
        var field = Metadata.ContainerType.GetProperty(Attribute.DependentProperty);
        if (field != null)
        {
            var value = field.GetValue(container,null);
            if ((value == null && Attribute.TargetValue == null) ||
                (value.Equals(Attribute.TargetValue)))
            {
                if (!Attribute.IsValid(Metadata.Model))
                    yield return new ModelValidationResult { Message = ErrorMessage };
            }
        }
    }
}

使用上面的代码,我需要在Global.asax.cs文件中注册:

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RequiredIfAttribute),typeof(RequiredIfValidator));

但是,如果我把所有内容都移动到属性中,我不必注册它:

public class RequiredIfAttribute : ValidationAttribute,object targetValue)
    {
        this.DependentProperty = dependentProperty;
        this.TargetValue = targetValue;
    }

    protected override ValidationResult IsValid(object value,ValidationContext validationContext)
    {
        var field = validationContext.ObjectInstance.GetType().GetProperty(DependentProperty);
        if (field != null)
        {
            var dependentValue = field.GetValue(validationContext.ObjectInstance,null);
            if ((dependentValue == null && TargetValue == null) ||
                (dependentValue.Equals(TargetValue)))
            {
                if (!innerAttribute.IsValid(value))
                    return new ValidationResult(ErrorMessage);
            }
        }
        return ValidationResult.Success;
    }

    public System.Collections.Generic.IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata,DependentProperty);
        yield return modelClientValidationRule;
    }
}

最后一位代码替换所有其他代码是否有问题?为什么要保留验证器类?

解决方法

CrazyDart,

在MVC3中添加了IClientValidatable界面.

第二个例子显示了这个新界面的有效使用.您没有必要注册是正确的,它将提供必要的客户端验证规则,以及进行必要的服务器端验证.

去吧,享受吧.

counsellorben

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读