【发布时间】:2011-06-08 03:17:02
【问题描述】:
我在进行 ASP.NET MVC 2 表单验证和设置样式时遇到问题。
这是我的表单示例,有一个验证错误:
该字段使用以下html:
<div class="registration-field">
<label>FullName</label><%= Html.TextBoxFor(x => x.FullName) %>
<%= Html.ValidationMessageFor(x => x.FullName)%>
</div>
问题是,为了在整个元素中显示高亮,我需要将 CSS 类“registration-field-error”添加到第一个 div。
<div class="registration-field registration-field-error">
<label>FullName</label><%= Html.TextBoxFor(x => x.FullName) %>
<%= Html.ValidationMessageFor(x => x.FullName)%>
</div>
registration-field-error 的 CSS 是:
.registration-field-error
{
background-image:url(../Content/Images/box-background-error.png);
background-repeat:repeat-y;
}
我可以做一些复杂的逻辑来检查 ViewState 是否有错误,这对于服务器验证错误很好,但不适用于客户端验证:
<% if (ViewData.ModelState["FullName"] == null) { %>
<div class="registration-field">
<% } else { %>
<div class="registration-field registration-field-error">
<% } %>
我的第一个想法是创建一个新的 Html 助手来决定它是否应该使用registration-field-error 类:
<%= Html.FormFieldFor(x => x.FullName, ViewData.ModelState) %>
然后编辑 MicrosoftMvc.Ajax.js 脚本以在检测到客户端验证错误时添加该类。
或者,有没有更好的方法来实现这一点?
【问题讨论】:
标签: jquery asp.net-mvc ajax model-view-controller