cpoDesign
cpoDesign

Reputation: 9143

Customise Validation summary

I have used html.ValidationSummary to get all errors displayed on top of the page. This will render list with errors on top of the page.

Example:

<ul>
<li>UserName is invalid</li>
</ul>

I have how ever need to render every item instead of list as custom div with additional html tags inside.

I need every line to be rendered as short example below (this is only one line):

<div>
<div class="right"><a href="#closeError">Close error</div>
<div class="right"><a href="#Update">Update Field</div>
<label>Error:</label> Name on the page is invalid.
</div>

What is your opininon how to achieve this rendering? I have considered to create html helper where i will take ModelState and get all errors, but not sure this will work...

Upvotes: 0

Views: 684

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038730

I have considered to create html helper where i will take ModelState and get all errors, but not sure this will work...

Why wouldn't that work?

public static class ValidationExtensions
{
    public static IHtmlString MyValidationSummary(this HtmlHelper htmlHelper)
    {
        var formContext = htmlHelper.ViewContext.ClientValidationEnabled 
            ? htmlHelper.ViewContext.FormContext 
            : null;
        if (formContext == null && htmlHelper.ViewData.ModelState.IsValid)
        {
            return null;
        }

        var sb = new StringBuilder();
        var htmlSummary = new TagBuilder("div");
        var modelStates = htmlHelper.ViewData.ModelState.Values;
        sb.AppendLine("<div class=\"right\"><a href=\"#closeError\">Close error</div>");
        sb.AppendLine("<div class=\"right\"><a href=\"#Update\">Update Field</div>");

        if (modelStates != null)
        {
            foreach (ModelState modelState in modelStates)
            {
                foreach (ModelError modelError in modelState.Errors)
                {
                    var userErrorMessageOrDefault = GetUserErrorMessageOrDefault(modelError);
                    if (!string.IsNullOrEmpty(userErrorMessageOrDefault))
                    {
                        sb.AppendFormat("<label>Error:</label> {0}{1}", htmlHelper.Encode(userErrorMessageOrDefault), Environment.NewLine);
                    }
                }
            }
        }

        htmlSummary.InnerHtml = sb.ToString();
        if (formContext != null)
        {
            formContext.ReplaceValidationSummary = true;
        }
        return MvcHtmlString.Create(htmlSummary.ToString(TagRenderMode.Normal));
    }

    private static string GetUserErrorMessageOrDefault(ModelError error)
    {
        if (!string.IsNullOrEmpty(error.ErrorMessage))
        {
            return error.ErrorMessage;
        }
        return null;
    }
}

and then:

<%= Html.MyValidationSummary() %>

Upvotes: 2

Related Questions