自定义数据注释,客户端验证,ViewModel和&示范州

时间:2013-11-06 21:08:43

标签: c# asp.net-mvc asp.net-mvc-3 data-annotations modelstate

这是此帖中较旧问题的扩展名:

Enforcing a model's boolean value to be true using data annotations

这让我对如何使用jquery-unubtrusive-ajax.js进行客户端自定义验证有了很多见解。

以下是答案代码:

            namespace Checked.Entitites
            {
                public class BooleanRequiredAttribute : ValidationAttribute, IClientValidatable
                {
                    public override bool IsValid(object value)
                    {
                        return value != null && (bool)value == true;
                    }

                    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
                    {
                        //return new ModelClientValidationRule[] { new ModelClientValidationRule() { ValidationType = "booleanrequired", ErrorMessage = this.ErrorMessage } };
                        yield return new ModelClientValidationRule() 
                        { 
                            ValidationType = "booleanrequired", 
                            ErrorMessage = this.ErrorMessageString 
                        };
                    }
                }
            }
  • 当我在模型中使用此自定义属性时,它可以正常工作。 例如:

            [BooleanRequired(ErrorMessage = "Please accept the terms")]
            public bool Terms { get; set; }
    
  • 当我在视图中使用textboxfor时,错误消息会填充在html验证摘要中。

            @Html.CheckBoxFor(model => model.Terms, new { @class = "legalbox",  @placeholder = "Terms" })
    
  • 我还必须将此行添加到我的jquery.unubtrusive-ajax.js

            $.validator.unobtrusive.adapters.addBool("BooleanRequired", "required"); 
    

当我在控制器中引用此模型并检查模型状态时,出现了我遇到此问题的问题。无论我拥有什么作为此自定义验证字段的值,模型状态始终为false。看起来覆盖无效是在客户端验证中工作但在服务器端不工作。我需要它在两者上工作并且一直在努力寻找一种不是“沟渠数据注释并使用其他东西”的解决方案。

我在控制器中使用的特定行将永远不会通过此字段:

            if (ModelState.IsValid) {
                 //Logic here
            }

使用标准数据注释的模型的其余部分正确验证,我只是不能使这个自定义的工作方式与内置属性相同。正确的解决方案可能会阻止我将该行添加到不显眼的ajax文件中。

任何帮助都将不胜感激。

由于

0 个答案:

没有答案