我正在使用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