ASP.NET MVC 2 验证错误样式
我在 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>
注册字段错误的 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 脚本以在检测到客户端验证错误时添加该类。
或者,有更好的方法来实现这一点吗?
I'm having trouble with my ASP.NET MVC 2 form validation and setting my style.
Here is an example of my form, with a validation error:
The field uses the following html:
<div class="registration-field">
<label>FullName</label><%= Html.TextBoxFor(x => x.FullName) %>
<%= Html.ValidationMessageFor(x => x.FullName)%>
</div>
The problem is, to show the highlight across the entire element, I need to add the CSS class "registration-field-error" to the first div.
<div class="registration-field registration-field-error">
<label>FullName</label><%= Html.TextBoxFor(x => x.FullName) %>
<%= Html.ValidationMessageFor(x => x.FullName)%>
</div>
The CSS for registration-field-error is:
.registration-field-error
{
background-image:url(../Content/Images/box-background-error.png);
background-repeat:repeat-y;
}
I can do some complicated logic to check the ViewState for errors, which works fine for server validation errors, but not for client-side validation:
<% if (ViewData.ModelState["FullName"] == null) { %>
<div class="registration-field">
<% } else { %>
<div class="registration-field registration-field-error">
<% } %>
My first thought was to make a new Html helper to decide if it should use the registration-field-error class:
<%= Html.FormFieldFor(x => x.FullName, ViewData.ModelState) %>
And then editing the MicrosoftMvc.Ajax.js script to add the class when it detects clientside validation errors.
Or, is there a better way to accomplish this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先将您的 div 元素包装在没有任何条件逻辑的情况下,但将您的验证消息包装在带有类名“error”的 span 中,如下所示:
然后使用下面给出的函数动态添加错误类:
这将更改代码的较少部分。
First wrap your div elements without any conditional logic but wrap your Validation Messages in span with class name "error" like below:
and then use a function given below to dynamically add the error classes:
This would be changing less parts of your code.