我只是列出复选框来选择开发人员有才华的语言。我喜欢验证必须至少选择一种语言。
服务器端验证没有失败。但是我无法让它在客户端工作。甚至从未调用过“GetClientValidationRules”方法。这就是我好奇的一点。
客户端验证不支持 IEnumerable 吗?这样做的方法是什么?
ps:我不需要放置js验证代码,因为我认为一旦调用GetClientValidationRules就可以了
视图:(为简洁起见)
public class DeveloperViewModel
{
[DeveloperLanguageSelectOneValidation(ErrorMessage="Please check at least one lang")]
public IEnumerable<SelectListItem> LanguagesModel { get; set; }
}
验证:
public class DeveloperLanguageSelectOneValidationAttribute : ValidationAttribute ,IClientValidatable
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
IEnumerable<SelectListItem> items = (IEnumerable<SelectListItem>)value;
foreach (var item in items)
if (item.Selected)
return ValidationResult.Success;
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule()
{
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
ValidationType = "developerlanguageselectone"
};
return new[] { rule };
}
}
选择列表项视图:
@model SelectListItem
<li>
@Html.HiddenFor(a => a.Value)
@Html.CheckBoxFor(a => a.Selected)
@Html.DisplayFor(a => a.Text)
</li>
开发者视图:
<ul>
@Html.EditorFor(a => a.LanguagesModel)</ul>
@Html.ValidationMessageFor(a => a.LanguagesModel)