好的,所以我有这些产品复选框,我想确保至少选择了一个产品。
为此,我的 ViewModel 包含:
[DisplayName(@"Product Line")]
[MinChecked(1)]
public List<CheckboxInfo> ActiveProducts { get; set; }
视图仅包含:
@Html.EditorFor(x => x.ActiveProducts)
该 EditorTemplate 包含:
@model Rad.Models.CheckboxInfo
@Html.HiddenFor(x => x.Value)
@Html.HiddenFor(x => x.Name)
@Html.CheckBoxFor(x => x.Selected)
@Html.LabelFor(x => x.Selected, Model.Name)
自定义数据注解为:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
public class MinCheckedAttribute : ValidationAttribute, IClientValidatable
{
public int MinValue { get; set; }
public MinCheckedAttribute(int minValue)
{
MinValue = minValue;
ErrorMessage = "At least " + MinValue + " {0} needs to be checked.";
}
public override string FormatErrorMessage(string propName)
{
return string.Format(ErrorMessage, propName);
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
try
{
List<CheckboxInfo> valueList = (List<CheckboxInfo>)value;
foreach (var valueItem in valueList)
{
if (valueItem.Selected)
{
return ValidationResult.Success;
}
}
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}
catch (Exception x)
{
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
ValidationType = "minchecked",
};
rule.ValidationParameters["minvalue"] = MinValue;
yield return rule;
}
}
jQuery部分是:
$.validator.addMethod('minchecked', function (value, element, params) {
var minValue = params['minvalue'];
alert(minValue);
$(element).each(function () {
if ($(this).is(':checked')) {
return true;
}
});
return false;
});
$.validator.unobtrusive.adapters.add('minchecked', ['minvalue'], function (options) {
options.messages['minchecked'] = options.message;
options.rules['minchecked'] = options.params;
});
因此,验证工作在服务器端。
但是,我如何让不显眼的验证工作?出于某种原因,
GetClientValidationRules
没有将 HTML5 附加到复选框。