[英]Client side validation mvc dropdown
@using (Html.BeginForm("ForatExcel", "ForatSummary", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.DropDownList("ForatFrom", new SelectList(Model, "ID", "ID", new { onchange = "getAllData()" }))
@Html.DropDownList("ForatTo", new SelectList(Model, "ID", "ID", new { onchange = "getAllData()" }))
<br />
<input type="submit" id="btnForatVersion" value="Go"/>
}
我需要驗證“ ForatFrom”下拉列表值是否大於“ ForatTo”值。 我猜我不能使用模型驗證,因為那只會檢查下拉列表的值是特定數字。 我在想也許jquery驗證,但不確定最好的選擇是什么?
謝謝
您可以並且應該使用模型驗證 。 我將實現一個驗證屬性[LargerThan],如下所示:
public class LargerThanAttribute: ValidationAttribute, IClientValidatable
{
private string _listPropertyName { get; set; }
public LargerThanAttribute(string listPropertyName)
{
this._listPropertyName = listPropertyName;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if(value == null)
return new ValidationResult("Not a valid value");
var listProperty = validationContext.ObjectInstance.GetType().GetProperty(_listPropertyName);
double propValue = Convert.ToDouble(listProperty.GetValue(validationContext.ObjectInstance, null));
if(propValue <= Convert.ToDouble(value))
return ValidationResult.Success;
return new ValidationResult("End value is smaller than start value");
}
}
請注意,此代碼未經測試,但是如果您沿這行寫一些東西並將其放在單獨的類中,則在需要進行此類檢查時都可以重用它。 您現在可以將其放在模型的屬性中
public double ForatFrom { get; set; }
[LargerThan("ForatFrom")]
public double ForatTo { get; set; }
現在,您可以進行服務器模型驗證,並且如果願意,現在可以實現jQuery非侵入式驗證。 我認為,如果需要驗證,則應至少在服務器上進行驗證;如果需要在客戶端上進行驗證,則也應在該位置上進行驗證,但絕不要僅依靠客戶機驗證。
這是一篇不錯的文章,您可以閱讀它,向您展示我剛才所做的事情,並說明如何實施客戶端驗證: http : //thepursuitofalife.com/asp-net-mvc-3-unobtrusive-javascript-validation-with-custom -validators /
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.