0
我有類似以下如何使用MVC3 Razor&Unobtrusive jQuery驗證驗證HiddenField?
public class TaskModel
{
public int UserId { get; set; }
public int CustomerId { get; set; }
public string CustomerDescription { get; set; }
/* Snip */
}
我如何添加驗證,以確保一個模式,在客戶端,代表CustomerId
一個隱藏字段是大於零?
@Html.LabelFor(x => x.CustomerId)
@Html.HiddenFor(x => x.CustomerId)
<label id="customerName" class="description">
@Model.CustomerName
</label>
只是爲了解釋上面發生了什麼;我使用彈出窗口從列表中選擇一個客戶,然後使用客戶的ID填充隱藏字段,並更新ID代表的客戶的標籤描述。我這樣做是爲了避免不必要的數據庫調用&。
我不想發佈表單數據以確定ID是否大於0.是否有一種簡單的方法將此作爲屬性添加到模型並讓它處理客戶端?我已經寫了下面的驗證屬性,但我不知道如何使它在客戶端無縫工作。
public class ValidIDAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
if (value == null)
{
return false;
}
else
{
if (value.GetType() == typeof(int))
{
return (int)value > 0;
}
else if (value.GetType() == typeof(Guid))
{
return (Guid)value != Guid.Empty;
}
return false;
}
}
}
謝謝,很好的訣竅...雖然文章似乎並沒有使用Unobtrusive?它使用MVC驗證? – GenericTypeTea
請參閱http://msdn.microsoft.com/en-us/vs2010trainingcourse_aspnetmvccustomvalidation_topic5#_Toc282145890 – SLaks