ASP.Net MVC:复选框的自定义客户端验证不起作用

时间:2016-03-25 20:08:40

标签: jquery asp.net-mvc data-annotations unobtrusive-validation asp.net-mvc-validation

基本上我在页面中显示复选框,在循环中生成复选框。 我使用此ValidationAttribute, IClientValidatable

创建了自定义验证

我的服务器端验证工作正常但客户端没有触发。 请看看我的代码并告诉我我犯了哪个错误。

我的目标

我希望用户必须选择一个爱好,这意味着用户必须选择一个复选框中的一个。

这样我生成复选框

    <div class="col-md-offset-2 col-md-10">
        <b>Hobbies</b><br />
        @for (int x = 0; x < Model.Hobbies.Count(); x++)
        {
            @Html.CheckBoxFor(p => p.Hobbies[x].IsSelected) @: &nbsp; 
            @Html.LabelFor(p => p.Hobbies[x].IsSelected, Model.Hobbies[x].Name) @: &nbsp;
            @Html.HiddenFor(p => p.Hobbies[x].Name) 
        }
        @Html.ValidationMessageFor(model => model.Hobbies)
    </div>

这样我可以注释我的视图模型属性

[AtleastOne(ErrorMessage = "Select at least one checkbox.")]
public List<Hobby> Hobbies { get; set; }

这是自定义验证的代码。

public class AtleastOneAttribute : ValidationAttribute, IClientValidatable
{
    // For Server side
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value != null)
        {
            var oHobby=value as IEnumerable;

            foreach (var _object in oHobby)
            {
                Hobby _oHobby = (Hobby)_object;
                if (_oHobby.IsSelected)
                {
                    return ValidationResult.Success;
                }
            }

        }
        return new ValidationResult(ErrorMessage);
    }
    // Implement IClientValidatable for client side Validation
    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule
        {
            ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
            ValidationType = "atleastonetrue",
        };
        yield return rule;
    }
}

客户端代码

<script type="text/javascript">

    $.validator.unobtrusive.adapters.add('atleastonetrue',  function (options) {
        //options.rules['restrictbackdates'] = { mindate: options.params.mindate };
        options.messages['atleastonetrue'] = options.message;
        alert('hello');
        alert(options.message);
    });

    $.validator.addMethod("atleastonetrue", function (value, element, param) {
        alert('hello');

        //var date = new Date(value);
        //var minDate = new Date(param.mindate);
        //return date >= minDate;
    });
</script>

我在我的代码中犯了错误,客户端代码没有被解雇?

感谢

修改

为复选框生成html

<div class="col-md-offset-2 col-md-10">
                <b>Hobbies</b><br>
<input type="checkbox" value="true" name="Hobbies[0].IsSelected" id="Hobbies_0__IsSelected" data-val-required="The IsSelected field is required." data-val="true"><input type="hidden" value="false" name="Hobbies[0].IsSelected">  &nbsp; 
<label for="Hobbies_0__IsSelected">Reading</label>  &nbsp;
<input type="hidden" value="Reading" name="Hobbies[0].Name" id="Hobbies_0__Name"><span data-valmsg-replace="true" data-valmsg-for="Hobbies[0].IsSelected" class="field-validation-valid"></span><input type="checkbox" value="true" name="Hobbies[1].IsSelected" id="Hobbies_1__IsSelected" data-val-required="The IsSelected field is required." data-val="true"><input type="hidden" value="false" name="Hobbies[1].IsSelected">  &nbsp; 
<label for="Hobbies_1__IsSelected">Sports</label>  &nbsp;
<input type="hidden" value="Sports" name="Hobbies[1].Name" id="Hobbies_1__Name"><span data-valmsg-replace="true" data-valmsg-for="Hobbies[1].IsSelected" class="field-validation-valid"></span><input type="checkbox" value="true" name="Hobbies[2].IsSelected" id="Hobbies_2__IsSelected" data-val-required="The IsSelected field is required." data-val="true"><input type="hidden" value="false" name="Hobbies[2].IsSelected">  &nbsp; 
<label for="Hobbies_2__IsSelected">Movies</label>  &nbsp;
<input type="hidden" value="Movies" name="Hobbies[2].Name" id="Hobbies_2__Name"><span data-valmsg-replace="true" data-valmsg-for="Hobbies[2].IsSelected" class="field-validation-valid"></span>                
            </div>

我的模型和ViewModel

  public class Product
    {
        public int ID { set; get; }
        public string Name { set; get; }
    }

    public class Hobby 
    {
        public string Name { get; set; }
        public bool IsSelected { get; set; }

    }

    public class SampleViewModel
    {
        [Display(Name = "Products")]
        public List<Product> Products { set; get; }

        [AtleastOne(ErrorMessage = "Select at least one checkbox.")]
        public List<Hobby> Hobbies { get; set; }

        [Required(ErrorMessage = "Select any Product")]
        public int SelectedProductId { set; get; }

        [Required(ErrorMessage = "Select Male or Female")]
        public string Gender { get; set; }
    }

0 个答案:

没有答案