Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the collection of Model State Errors in ASP.NET MVC?

How do I get the collection of errors in a view?

I don't want to use the Html Helper Validation Summary or Validation Message. Instead I want to check for errors and if any display them in specific format. Also on the input controls I want to check for a specific property error and add a class to the input.

P.S. I'm using the Spark View Engine but the idea should be the same.

So I figured I could do something like...

<if condition="${ModelState.Errors.Count > 0}">   DisplayErrorSummary() </if>  ....and also...  <input type="text" value="${Model.Name}"         class="?{ModelState.Errors["Name"] != string.empty} error" />  .... 

Or something like that.

UPDATE

My final solution looked like this:

<input type="text" value="${ViewData.Model.Name}"         class="text error?{!ViewData.ModelState.IsValid &&                             ViewData.ModelState["Name"].Errors.Count() > 0}"         id="Name" name="Name" /> 

This only adds the error css class if this property has an error.

like image 351
rmontgomery429 Avatar asked Feb 21 '09 16:02

rmontgomery429


People also ask

How do I get model state errors?

You can use SelectMany function c# to get error message from modelstate mvc. It will generate error message string it contains modelstate errors; we can return as json and display in html element. You have to define validations inside the class as per requirement.

How do I display model state errors in view?

To pass error to the view we can use ModelState. AddModelError method (if the error is Model field specific) or simply ViewBag or ViewData can also be used.

What is a ModelState asp net?

In short, the ModelState is a collection of name and value pairs that are submitted to the server during a POST. It also contains error messages about each name-value pair, if any are found. ModelState is a property of a Controller instance, and can be accessed from any class that inherits from Microsoft. AspNetCore.


1 Answers

<% ViewData.ModelState.IsValid %> 

or

<% ViewData.ModelState.Values.Any(x => x.Errors.Count >= 1) %> 

and for a specific property...

<% ViewData.ModelState["Property"].Errors %> // Note this returns a collection 
like image 141
Chad Moran Avatar answered Sep 18 '22 19:09

Chad Moran