Perhaps, like me, you find yourself maintaining an ASP.NET MVC web application and you need to find the number of errors added to the ModelState. Of course, you may think that you can just use something like ModelState.Count, but this will not give you the number of errors added via the ModelState.AddModelError() function. In order to get the actual count of the errors added you can use the following method:

int errorCount = ModelState.Sum(x => x.Value.Errors.Count);

If course, at times you just want to know if ModelState has had any errors added. If you want to do this you can use something like the following:

bool hasAnError = ModelState.Any(x => x.Value.Errors.Count > 0);

I hope this snippet can help developers like myself who are new to ASP.NET but have to maintain and better old code. As always, happy coding!!! šŸ˜Ž

Categories: Blog

Leave a Reply

Your email address will not be published. Required fields are marked *