Skip to content

Instantly share code, notes, and snippets.

@jpoehls
Created March 28, 2012 20:30
Show Gist options
  • Select an option

  • Save jpoehls/2230255 to your computer and use it in GitHub Desktop.

Select an option

Save jpoehls/2230255 to your computer and use it in GitHub Desktop.
Get dictionary of errors from ModelState in ASP.NET MVC
var errorList = ModelState
.Where(x => x.Value.Errors.Count > 0)
.ToDictionary(
kvp => kvp.Key,
kvp => kvp.Value.Errors.Select(e => e.ErrorMessage).ToArray()
);
@extreme007

Copy link
Copy Markdown

fdasfasfsa

@CesarNicolini

Copy link
Copy Markdown

thanks

@Barbanyaga

Copy link
Copy Markdown

Thanks a lot, useful

@GrantByrne

Copy link
Copy Markdown

Thank you. This was helpful.

@camilopedroso

Copy link
Copy Markdown

Thanks a lot!

@olakusibe

Copy link
Copy Markdown

Still saving lives. Thanks

@francofgp

Copy link
Copy Markdown

Thanks!

@migueloliveiradev

Copy link
Copy Markdown

UwU

@enggomarpu

Copy link
Copy Markdown

@jpoehls please can you explain how the code is working ? because I am seeing "Values" and "Keys" in the model state. What exactly "x" is referring to in the code ?

@jpoehls

jpoehls commented Mar 30, 2024

Copy link
Copy Markdown
Author

@jpoehls please can you explain how the code is working ? because I am seeing "Values" and "Keys" in the model state. What exactly "x" is referring to in the code ?

“x” is the KeyValuePair<> in the ModelStateDictionary. You can read the docs on that Type here: https://learn.microsoft.com/en-us/dotnet/api/system.web.mvc.modelstatedictionary?view=aspnet-mvc-5.2

@enggomarpu

enggomarpu commented Mar 30, 2024

Copy link
Copy Markdown

@jpoehls I got you but why am I not able to see KeyValuePairs directly in the breakpoint. They are coming in the Values and Keys. This thing is confusing me. or will we loop according to things which is coming in "Result View" ?
image

@jpoehls

jpoehls commented Mar 30, 2024

Copy link
Copy Markdown
Author

@jpoehls I got you but why am I not able to see KeyValuePairs directly in the breakpoint. They are coming in the Values and Keys. This thing is confusing me. or will we loop according to things which is coming in "Result View" ? image

You may be able to expand the Results View or Non-Public members to explore the pairs. I'm afraid I can't offer more specific help.

@enggomarpu

Copy link
Copy Markdown

@jpoehls Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment