Reputation: 14931
I want to customize the html output of ValidationSummary in ASP.NET MVC 2
from
<div class="validation-summary-errors">
<span>Oops! validation was failed because:</span>
<ul>
<li>The Title field is required.</li>
<li>The Body field is required.</li>
</ul>
</div>
to
<div class="validation-error">
<p>Oops! validation was failed because:</p>
<ul>
<li>The Title field is required.</li>
<li>The Body field is required.</li>
</ul>
</div>
Is there any new way in asp.net MVC 2 to solve this?
Upvotes: 4
Views: 5054
Reputation:
Alternatively, you could reference that span through CSS and style it as a p.
This is the way to reference it -you'll need to style it accordingly:
.validation-summary-errors > span { margin: 0px; }
Upvotes: 2
Reputation: 26599
There doesn't seem to be any way to do it with templating, which is pretty poor. If you take a look at the code for this particular helper method you'll see the HTML is baked into the method itself:
public static string ValidationSummary(this HtmlHelper htmlHelper, string message, IDictionary<string, object> htmlAttributes) {
// Nothing to do if there aren't any errors
if (htmlHelper.ViewData.ModelState.IsValid) {
return null;
}
string messageSpan;
if (!String.IsNullOrEmpty(message)) {
TagBuilder spanTag = new TagBuilder("span");
spanTag.MergeAttributes(htmlAttributes);
spanTag.MergeAttribute("class", HtmlHelper.ValidationSummaryCssClassName);
spanTag.SetInnerText(message);
messageSpan = spanTag.ToString(TagRenderMode.Normal) + Environment.NewLine;
}
else {
messageSpan = null;
}
StringBuilder htmlSummary = new StringBuilder();
TagBuilder unorderedList = new TagBuilder("ul");
unorderedList.MergeAttributes(htmlAttributes);
unorderedList.MergeAttribute("class", HtmlHelper.ValidationSummaryCssClassName);
foreach (ModelState modelState in htmlHelper.ViewData.ModelState.Values) {
foreach (ModelError modelError in modelState.Errors) {
string errorText = GetUserErrorMessageOrDefault(htmlHelper.ViewContext.HttpContext, modelError, null /* modelState */);
if (!String.IsNullOrEmpty(errorText)) {
TagBuilder listItem = new TagBuilder("li");
listItem.SetInnerText(errorText);
htmlSummary.AppendLine(listItem.ToString(TagRenderMode.Normal));
}
}
}
}
The good news is, with MVC being open source, you can go and grab the source from the CodePlex repository and tweak it any way you like.
Upvotes: 6