How do I find out the error count in a ASP.NET MVC View?
Asked Answered
G

3

7

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?

Glossographer answered 10/2, 2010 at 17:26 Comment(0)
F
18

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

ViewData.ModelState.Values.Where( v => v.Errors.Count != 0 ).Count()
Frontolysis answered 10/2, 2010 at 17:36 Comment(0)
U
2

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.

Unmade answered 10/2, 2010 at 17:31 Comment(0)
K
2

You can also use an easier way

@if (ViewData.ModelState.ErrorCount > 0)
{
  ...
}
Kosse answered 17/1, 2020 at 10:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.