问题描述
我正在使用 Asp.Net MVC3 开发一个项目
在视图中我有 @Html.ValidationSummary(true)
并且通常它会产生
<ul><li>发生了不好的事情!</li>
如何将此 ValidationSummary 扩展到 MyValidationSummary 并生成如下所示的 Html 代码模板:
<span></span><div class="text"><p>发生了不好的事情!</p>
我正在使用 Asp.Net MVC3 开发一个项目
在视图中我有 @Html.ValidationSummary(true)
并且通常它会产生
<ul><li>发生了不好的事情!</li>
如何将此 ValidationSummary 扩展到 MyValidationSummary 并生成如下所示的 Html 代码模板:
<span></span><div class="text"><p>发生了不好的事情!</p>
这个 问题 详细说明了编写自定义验证摘要的过程.
编辑这将执行您想要的操作:
公共静态类LinqExt{公共静态字符串 MyValidationSummary(这个 HtmlHelper 助手,字符串验证消息 ="){字符串 retVal = "";如果(helper.ViewData.ModelState.IsValid)返回 "";retVal += "";如果 (!String.IsNullOrEmpty(validationMessage))retVal += helper.Encode(validationMessage);retVal += "</span>";retVal += "";foreach (var key in helper.ViewData.ModelState.Keys){foreach(var err in helper.ViewData.ModelState[key].Errors)retVal += ""+ helper.Encode(err.ErrorMessage) + "</p>";}retVal += "</div></div>";返回 retVal.ToString();}}
代码是不言自明的;只是在您选择的 dom 元素中枚举模型状态错误和包装错误.有一个错误,如果我像这样使用它:
它将在页面上将 html 标签显示为文本而不是呈现它.
这很好用.
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>
解决方案 This question details the procedure of writing custom validation summary.
EDITThis 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.
这篇关于自定义 ValidationSummary 模板 Asp.net MVC 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-09 02:51