简体   繁体   中英

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

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?

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

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

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.

You can also use an easier way

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM