简体   繁体   中英

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>

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

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>
<% } %>

对于MVC 2,ValidationSummary是一种扩展方法,您必须添加

using System.Web.Mvc.Html;

例如,将此CSS用于li标签...

.validation-summary-errors ul li {color:Red;}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM