validationsummaryasp.net-mvc-3

Custom ValidationSummary template Asp.net MVC 3


I am working on a project with Asp.Net MVC3

In a View I have @Html.ValidationSummary(true) and as usually it produces

<div class="validation-summary-errors">
    <ul>
        <li>Something bad Happened!</li>
    </ul>
</div>

How can I extend this ValidationSummary to MyValidationSummary and produces the Html Code template something like this:

<div class="notification warning"> 
    <span></span> 
    <div class="text"> <p>Something bad Happened!</p> </div> 
</div>

Solution

  • This question details the procedure of writing custom validation summary.

    EDIT This will do what you want:

    public static class LinqExt 
    {
        public static string MyValidationSummary(this HtmlHelper helper, string validationMessage="")
        {
            string retVal = "";
            if (helper.ViewData.ModelState.IsValid)
                return "";
    
            retVal += "<div class='notification-warnings'><span>";
            if (!String.IsNullOrEmpty(validationMessage))
                retVal += helper.Encode(validationMessage);
            retVal += "</span>";
            retVal += "<div class='text'>";
            foreach (var key in helper.ViewData.ModelState.Keys) 
            {
                foreach(var err in helper.ViewData.ModelState[key].Errors)
                    retVal += "<p>" + helper.Encode(err.ErrorMessage) + "</p>";
            }
            retVal += "</div></div>";
            return retVal.ToString();
        }
    }
    

    The code is self explanatory; just enumerating through modelstate errors and wrapping errors in dom element of your choice. There is an error that is if i use it like:

    <%:Html.MyValidationSummary()%>
    

    It will display html tags on the page as text rather than rendering it.

    <%=Html.MyValidationSummary()%>
    

    This works fine.