gpt4 book ai didi

asp.net-mvc-2 - 在 ASP.NET MVC 2 中自定义 ValidationSummary

转载 作者:行者123 更新时间:2023-12-02 03:38:25 25 4
gpt4 key购买 nike

我想在 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 有没有新的方法来解决这个问题?

最佳答案

似乎没有任何方法可以通过模板来做到这一点,这非常糟糕。如果您查看此特定辅助方法的代码,您将看到 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 开源,您可以从 the CodePlex repository 获取源代码并按照您喜欢的方式进行调整。

关于asp.net-mvc-2 - 在 ASP.NET MVC 2 中自定义 ValidationSummary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2910340/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com