3
好的,所以我有這些產品的複選框,我想確保至少選擇一個產品。多個複選框的自定義DataAnnotation
要做到這一點,我的視圖模型包含:
[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)
定製dataannotation是:
[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附加到複選框。
斷點是否會碰到GetClientValidationRules? – frictionlesspulley
不,不。這就是我問的問題,是如何讓它重視。 – ScubaSteve