我正在使用ASP.NET MVC 5并在客户端希望使用JQuery不显眼的验证。ASP.NET MVC自定义验证列表<string>
以下是我的模型:
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属性填充的值集合的所有元素。
任何想法?
供参考:html中的dependentpropertyId填充像EmployeeModel.Employees_0_IsRequired for Employee [0]一样。
您无法获取jQuery客户端端v因为您无法为集合生成表单控件(仅针对集合的属性),因此属性是集合的alidation。您需要编写自己的客户端脚本才能显示您自己的客户端消息。 –
好的,谢谢我看到。 @StephenMuecke然后你建议做一些类似于这里所接受的答案的东西。 http://stackoverflow.com/questions/5662589/unobtrusive-mvc3-validating-group-of-checkboxes或手动添加data-val和data-val-requiredif属性到html,然后编写一个jQuery验证适配器? – user1527762
@Sparky(http://stackoverflow.com/users/594235/sparky)同样的问题也给你了吗? – user1527762