使用EditorFor for List <t> </t>时,客户端验证不会显示消息

时间:2014-06-19 10:00:45

标签: c# javascript asp.net-mvc-4

我有一个简单的模型:

public class MyModel {
    public int Id { get; set; }

    [MyValidation]
    public CheckBoxModel IList<Options> { get; set; }
}

CheckBoxModel是:

public class CheckBoxModel {
   public int Id { get; set; }
   public bool IsChecked { get; set; }
}

MyValidation课程:

public class MyValidationAttribute : ValidationAttribute, IClientValidatable {
    public IEnumerable<ModelClientValidationRule> GetClientValidationRules( ModelMetadata metadata,
         ControllerContext context )
      {
         yield return new ModelClientValidationRule {ValidationType = "requiredgroup"};
      }

public override bool IsValid( object value )
      {
         // logic here
      }
}

好的,我们还会向您展示观点:

<div class="test">
   @Html.EditorFor(model=>model.Options)
   @Html.ValidationMessageFor(model=>model.Options)
</div>

编辑器模板看起来像CheckBoxModel.cshtml

<div>
   @Html.CheckBoxFor(m=>m.IsChecked, new {data_val_requiredgroup = "One item should be checked"})
   ...
</div>

EditorFor生成的HTML看起来像

<div>
   <input type="checkbox" id="Options[0].IsChecked" name="Options[0]_IsChecked" data-val-required-group="One item should be checked"/>
</div>

自定义javascript验证:

$.validator.unobtrusive.adapters.add('requiredgroup', {}, function (options) {
   options.rules['requiredgroup'] = true;
   options.messages['requiredgroup'] = options.message;
});

$.validator.addMethod('requiredgroup', function(value, element, params) {
   var $module = $(element).parents('form');
   var result = $module.find('input[type="checkbox"][data-val-requiredgroup]:checked').length;

   return result;
});

客户端验证有效(表单提交已取消并保留在同一页面上),但未显示错误。

如何实现这一目标?如何在@Html.ValidationMessageFor(model=>model.Options)中显示错误消息?

1 个答案:

答案 0 :(得分:1)

您的自定义验证类需要从ValidationAttribute类继承,并将错误消息传递给基础构造函数。

public class DummyAttribute : ValidationAttribute, IClientValidatable
{
    public DummyAttribute() : base("{0} contains invalid data.")
    ....
}