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

后端 未结 4 479
北恋
北恋 2020-12-03 02:13

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?

相关标签:
4条回答
  • 2020-12-03 02:35

    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>
    <% } %>
    
    0 讨论(0)
  • For MVC 2, ValidationSummary is a extension method, you must add

    using System.Web.Mvc.Html;
    
    0 讨论(0)
  • 2020-12-03 02:40

    Use this CSS for li tag for example...

    .validation-summary-errors ul li {color:Red;}
    
    0 讨论(0)
  • 2020-12-03 02:47

    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

    0 讨论(0)
提交回复
热议问题