【发布时间】:2016-03-07 17:17:37
【问题描述】:
我正在使用 ASP.NET MVC 5,并且在客户端想要使用 JQuery 不显眼的验证。
以下是我的模型:
public class CompanyModel
{
public CompanyModel()
{
Employees = new List<EmployeeModel>();
}
public int CompanyId{ get; set; }
public List<EmployeeModel> Employees { get; set; }
}
public class EmployeeModel
{
public EmployeeModel()
{
Values = new List<string>();
}
public string Id { get; set; }
public string Name { get; set; }
[RequiredIf("IsRequired", true, "Atleast one value is required")]
public List<string> Values { get; set; }
public bool IsRequired { get; set; }
}
我能够在服务器端成功实现RequiredIf 自定义属性。但是我正在努力进行客户端验证...
在视图中,我遍历员工列表并绑定了值集合
@for (var index = 0; index < Model.Employees.Count; index++)
{
/// some other code
@for (int i = 0; i < Model.employees[index].Values.Count; i++)
{
@Html.TextBoxFor(m => m.Employees[index].Values[i], new {@autocomplete = "false" })
}
}
IsRequired 属性是一个隐藏字段:
@Html.HiddenFor(m => m.Employees[index].IsRequired)
以下是我目前为 GetClientValidationRules 方法编写的代码。
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = ErrorMessage,
ValidationType = "requiredif"
};
rule.ValidationParameters["dependentproperty"] = (context as ViewContext).ViewData.TemplateInfo.GetFullHtmlFieldId(DependentProperty);
rule.ValidationParameters["dependentpropertyvalue"] = DependentPropertyValue.ToString().ToLower();
yield return rule;
}
我没有看到将验证 html (data-val-*) 属性添加到 HTML 标记中的值。而且我也不指望他们,因为我认为我错过了一些东西。如何在 html 中获取使用 data-val-requiredif 属性填充的 values 集合的所有元素。
有什么想法吗?
仅供参考:html 中的dependentpropertyId 填充为 CompanyModel.Employees_0_IsRequired for Employee[0]。
【问题讨论】:
-
您无法为集合的属性获取 jquery 客户端验证,因为您无法为集合生成表单控件(仅适用于集合的属性)。您需要编写自己的客户端脚本才能显示您自己的客户端消息。
-
好的,谢谢,我明白了。 @StephenMuecke 然后你建议做一些类似于接受的答案在这里建议的事情。 stackoverflow.com/questions/5662589/… 还是手动给html添加data-val和data-val-requiredif属性然后写一个jquery验证适配器?
-
@Sparky(stackoverflow.com/users/594235/sparky) 你也有同样的问题吗?
-
我对 ASP 或其 Unobtrusive 插件了解不多,但就 jQuery Validate 而言,不需要特殊方法来验证一组复选框或单选按钮。见:jsfiddle.net/af68u6z3
-
我也看不到你渲染的 HTML,所以我不知道
List<string>应该是什么。但是,使用 jQuery Validate 只能验证textarea、select和各种类型的input元素;没有别的。
标签: jquery asp.net-mvc asp.net-mvc-4 unobtrusive-validation