How to extend the ValidationSummary HTML Helper in ASP.NET MVC?

I need to wrap the Validation Summary in a div. How do I set the Validation Summary to wrap it with a div when errors are present?

<div class="validation-summary"> 
  <%= Html.ValidationSummary("Login was unsuccessful. Please correct the errors and try again.") %>
</div>

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

I had to extend the validation summary extensions in another project of mine to deal with more than one form on a page.

Although this is different, you could create your own extension method…

namespace System.Web.Mvc
{
    public static class ViewExtensions
    {
        public static string MyValidationSummary(this HtmlHelper html, string validationMessage)
        {
            if (!html.ViewData.ModelState.IsValid)
            {
                return "<div class="validation-summary">" + html.ValidationSummary(validationMessage) + "</div>"
            }

            return "";
        }
    }
}

Then just call
<%= Html.MyValidationSummary(
    "Login was unsuccessful. Please correct the errors and try again.") %>

HTHs,
Charles

Method 2

What you can do is this :

<%if (!ViewData.ModelState.IsValid) { %>
<div class="validation-summary"> 
    <%= Html.ValidationSummary(
        "Login was unsuccessful. Please correct the errors and try again.") %>
</div>
<% } %>

Method 3

For MVC 2, ValidationSummary is a extension method, you must add

using System.Web.Mvc.Html;

Method 4

Use this CSS for li tag for example…

.validation-summary-errors ul li {color:Red;}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x