Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 651
craigmoliver Avatar asked May 28 '09 02:05

craigmoliver


People also ask

What is HTML ValidationSummary in MVC?

ValidationSummary(HtmlHelper, Boolean, String, IDictionary<String,Object>) Returns an unordered list (ul element) of validation messages that are in the ModelStateDictionary object and optionally displays only model-level errors.

What is the main purpose of HTML helper of ActionLink in ASP NET MVC?

Html. ActionLink creates a hyperlink on a view page and the user clicks it to navigate to a new URL. It does not link to a view directly, rather it links to a controller's action.

How do I create a custom error message in ValidationSummary?

AddModelError() method. The ValidationSummary() method will automatically display all the error messages added in the ModelState . Thus, you can use the ValidationSummary helper method to display error messages.


1 Answers

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

like image 69
Charlino Avatar answered Oct 20 '22 17:10

Charlino