4

我想在 ASP.NET MVC 2 中自定义 ValidationSummary 的 html 输出

<div class="validation-summary-errors">
    <span>Oops! validation was failed because:</span>
    <ul>
        <li>The Title field is required.</li>
        <li>The Body field is required.</li>
    </ul>
</div>

<div class="validation-error">
    <p>Oops! validation was failed because:</p>
    <ul>
        <li>The Title field is required.</li>
        <li>The Body field is required.</li>
    </ul>
</div>

asp.net MVC 2 中有什么新方法可以解决这个问题吗?

4

2 回答 2

6

模板似乎没有任何方法可以做到这一点,这很糟糕。如果您查看此特定辅助方法的代码,您会看到 HTML 已融入方法本身:

public static string ValidationSummary(this HtmlHelper htmlHelper, string message, IDictionary<string, object> htmlAttributes) {
    // Nothing to do if there aren't any errors
    if (htmlHelper.ViewData.ModelState.IsValid) {
        return null;
    }

    string messageSpan;
    if (!String.IsNullOrEmpty(message)) {
        TagBuilder spanTag = new TagBuilder("span");
        spanTag.MergeAttributes(htmlAttributes);
        spanTag.MergeAttribute("class", HtmlHelper.ValidationSummaryCssClassName);
        spanTag.SetInnerText(message);
        messageSpan = spanTag.ToString(TagRenderMode.Normal) + Environment.NewLine;
    }
    else {
        messageSpan = null;
    }

    StringBuilder htmlSummary = new StringBuilder();
    TagBuilder unorderedList = new TagBuilder("ul");
    unorderedList.MergeAttributes(htmlAttributes);
    unorderedList.MergeAttribute("class", HtmlHelper.ValidationSummaryCssClassName);

    foreach (ModelState modelState in htmlHelper.ViewData.ModelState.Values) {
        foreach (ModelError modelError in modelState.Errors) {
            string errorText = GetUserErrorMessageOrDefault(htmlHelper.ViewContext.HttpContext, modelError, null /* modelState */);
            if (!String.IsNullOrEmpty(errorText)) {
                TagBuilder listItem = new TagBuilder("li");
                listItem.SetInnerText(errorText);
                htmlSummary.AppendLine(listItem.ToString(TagRenderMode.Normal));
            }
        }
    }
}

好消息是,由于 MVC 是开源的,您可以从CodePlex 存储库中获取源代码,并以您喜欢的方式对其进行调整。

于 2010-05-26T06:05:06.107 回答
2

或者,您可以通过 CSS 引用该跨度并将其设置为 p。

这是引用它的方式 - 您需要相应地设置它的样式:

.validation-summary-errors > span { margin: 0px; }
于 2010-07-31T20:26:50.050 回答