如何找出 ASP.NET MVC 视图中的错误计数?

发布于 2024-08-20 19:08:43 字数 137 浏览 1 评论 0原文

我想使用类似以下内容的字符串来格式化验证摘要的标题:

"There are {0} errors on this page."

如何找出错误数,而不在控制器中进行操作并将其添加到“查看数据”?

I want to format the title of my Validation Summary using a string something like:

"There are {0} errors on this page."

How do I find out the number of errors without doing it in the controller and adding it to View Data?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

吲‖鸣 2024-08-27 19:08:43

我想你的意思是从观点来看。以下未经测试。

ViewData.ModelState.Values.Where( v => v.Errors.Count != 0 ).Count()

I assume you mean from the view. The following is untested.

ViewData.ModelState.Values.Where( v => v.Errors.Count != 0 ).Count()
一个人的夜不怕黑 2024-08-27 19:08:43

如果您指的是 IEnumerable的 ASP.NET MVC 1.0 版本,您可以通过以下方式获取计数:

var errorCount = GetRuleViolations().Count();

要将该计数获取到视图中而不将其放入视图数据中,您可以:您可以为 ValidationSummary HtmlHelper 扩展方法创建一个重载,该方法返回包含错误计数的文本。这使您可以从扩展方法内访问错误计数。

要查看原始 ValidationSummary 扩展方法中的代码,可以使用 Reflector 对其进行反编译,或者从 Codeplex 下载 ASP.NET MVC 源代码。

请注意,ASP.NET MVC 2.0 中的验证机制发生了重大变化。

If you are referring to the ASP.NET MVC 1.0 version of IEnumerable<RuleViolation>, you can get the count this way:

var errorCount = GetRuleViolations().Count();

To get that count into the view without putting it into view data, you can, you can create an overload for the ValidationSummary HtmlHelper extension method that returns text which includes the error count. This gives you access to the error count from within the extension method.

To see the code in the original ValidationSummary extension method, you can use Reflector to decompile it, or download the ASP.NET MVC source from Codeplex.

Note that the validation mechanism has changed substantially in ASP.NET MVC 2.0.

羁拥 2024-08-27 19:08:43

您还可以使用更简单的方法

@if (ViewData.ModelState.ErrorCount > 0)
{
  ...
}

You can also use an easier way

@if (ViewData.ModelState.ErrorCount > 0)
{
  ...
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文