ASP.NET MVC 2 Validation Error Styles
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?
First wrap your div elements without any conditional logic but wrap your Validation Messages in span with class name "error" like below:
<div class="registration-field">
<label>FullName</label><%= Html.TextBoxFor(x => x.FullName) %>
<span class="error"><%= Html.ValidationMessageFor(x => x.FullName)%></span>
</div>
and then use a function given below to dynamically add the error classes:
$(function(){
$("div span.error").each(function(){
var className = $(this).parent().attr("class") + "-error";
if($(this).html().length > 1)
$(this).parent().addClass(className);
});
});
This would be changing less parts of your code.
精彩评论