我有以下視圖模型:ASP.NET MVC 3客戶端驗證
public class ViewModel
{
[Display(Name = "firstname", ResourceType = typeof(Views.Validation))]
public string firstname { get; set; }
[Required(ErrorMessageResourceName="required", ErrorMessageResourceType = typeof(Views.Validation))]
[Display(Name="lastname", ResourceType = typeof(Views.Validation))]
public string lastname { get; set; }
...
}
和我的HTML視圖:
...
<div class="row valid showMsg">
<div class="itemWrap clearfix">
<label>@Html.LabelFor(model => model.firstname)<span class="iconReq"> </span>:</label>
@Html.EditorFor(model => model.firstname)
</div>
<div class="info">
<p class="errorMsg">@Html.ValidationMessageFor(model => model.firstname)</p>
<p class="infoMsg">info message here</p>
<p class="focusMsg">text on active</p>
</div>
</div>
...
如果你在我的HTML視圖請注意,我有一個類<div class="row valid showMsg">
「 showMsg「來控制我的<div class="info">
中的消息顯示。現在
,服務器驗證我寫了一個自定義HTML幫手補充說,那類「showMsg」到div時無效像這樣:
public static MvcHtmlString ValidationRowFor<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression)
{
MvcHtmlString normal = html.ValidationMessageFor(expression);
if (normal != null)
{
return MvcHtmlString.Create("errorOn");
}
return null;
}
,並使用它,像這樣:
<div class="row valid @Html.ValidationRowFor(model => model.firstname)">
我想爲客戶端驗證做同樣的事情。所以它會自動添加「showMsg」類時父錯誤。我會怎麼做?
謝謝。
編輯: 確定這適用於普通的HTML但不適用於MVC3?
$(function(){
var validator = $(".form").validate({
highlight: function(element) {
$(element).parents().closest('div.row').addClass('errorOn');
},
unhighlight: function(element) {
$(element).parents().closest('div.row').removeClass('errorOn');
}
});
});
隨着客戶端驗證你的意思是jQuery的或這樣的事情,幫助您處理數據驗證和顯示錯誤? – 2011-01-25 08:00:46
是的。我想'注入'或修改'jQuery.validate.unobtrusive.min.js'在ASP.NET MVC 3'新的'不顯眼的客戶端驗證',所以它會自動爲我做。這意味着它會爲每個無效條目添加該類。 – ShaneKm 2011-01-25 08:30:25