Adding a container to ValidationSummary helper in ASP.NET MVC
The one thing that is annoying about the validation summary HTML Helper in ASP.NET MVC is that it doesn't render a container element. Problem solved...
The source code below uses an Extension method to append the method ValidationSummaryWithContainer to the HtmlHelper class. This method works by grabbing the actual ValidationSummary first, checking to see if it has output any content, and if it has, wrapping a div element around the generated output. It's pretty simple, but effective.
using System.Text;
namespace System.Web.Mvc.Html
{
public static class ValidationSummaryExtension
{
/// <summary>
/// Creates a validation summary with a container element
/// surrounding the summary and error messages.
/// </summary>
public static string ValidationSummaryWithContainer(this HtmlHelper ext, string message)
{
var summaryoutput = ext.ValidationSummary(message);
if (!string.IsNullOrEmpty(summaryoutput))
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("<div class='validation-summary-errors-container'>");
sb.Append(summaryoutput);
sb.Append("</div>");
return sb.ToString();
}
else
return string.Empty;
}
}
}
To use this helper, on your view page, just call the helper method as you normally would:
If there are no errors, it will render nothing, if there are errors, it will render the output with a containing div element.
<span class="validation-summary-errors">Please fix the following errors:</span>
<ul class="validation-summary-errors">
<li>Title is required.</li>
<li>Description is required.</li>
<li>Contact email address is required.</li>
<li>Specific area is required.</li>
<li>Recaptcha was not valid, please try again.</li>
</ul>
</div>
Finally, the whole point of this exercise, is so that you can add css style to the containing element and make your error's very pretty.
/* VALIDATION ERROR*/
.validation-summary-errors-container
{
padding: 1.5em;
margin: .5em 0px .5em 0px;
background-color: #ffffdf;
border: 1px solid #df6b6b;
color: #dc3535;
}
.field-validation-error
{
color: #dc3535;
}
.input-validation-error
{
border: 1px solid #df6b6b;
background-color: #ffffdf;
}
span.validation-summary-errors
{
font-weight: bold;
}
Recent blog posts
- Canned VirtualPC Instances for IE 6, 7, 8 on XP/Vista
- Checking assembly dependencies for .NET
- Google's Public DNS
- Server Utility Functions for Non-Web Apps
- reCAPTCHA for ASP.NET MVC that uses ModelState
- Adding a container to ValidationSummary helper in ASP.NET MVC
- Generic XML Serialization Class
- Re-throwing Exceptions in C# with InternalPreserveStackTrace
- Solving xsd generation error: 'The element .... is missing'
- Enum DropDownList in ASP.NET MVC
Recent comments
9 weeks 2 days ago
12 weeks 3 days ago
15 weeks 4 days ago
21 weeks 2 days ago
31 weeks 1 day ago
1 year 15 weeks ago
1 year 32 weeks ago
1 year 33 weeks ago
1 year 39 weeks ago
2 years 16 weeks ago