2 Replies - 579 Views - Last Post: 04 October 2019 - 06:07 AM Rate Topic: -----

#1 andrewsw   User is offline

  • never lube your breaks
  • member icon

Reputation: 6819
  • View blog
  • Posts: 28,246
  • Joined: 12-December 12

ModelState get friendly error message

Posted 04 October 2019 - 04:50 AM

(ASP.NET MVC)

There is an error with an email field in the ModelState. The original code to try and obtain the first error message was:

errMess = ModelState.Select(x => x.Value.Errors).FirstOrDefault().ToString();

yielding

Quote

System.Web.Mvc.ModelErrorCollection


which isn't particularly helpful.

With reference to this SO page I modified to:

errMess = ModelState.Select(x => x.Value.Errors.Select(err => err.ErrorMessage)).FirstOrDefault().ToString();

yielding

System.Linq.Enumerable+WhereSelectEnumerableIterator`2[System.Web.Mvc.ModelError,System.String]

Again, not too fruitful.

Is this something you have encountered and resolved? Thanks for any advice.

Is This A Good Question/Topic? 0
  • +

Replies To: ModelState get friendly error message

#2 andrewsw   User is offline

  • never lube your breaks
  • member icon

Reputation: 6819
  • View blog
  • Posts: 28,246
  • Joined: 12-December 12

Re: ModelState get friendly error message

Posted 04 October 2019 - 05:40 AM

I think I have it sussed with this:

                foreach (ModelState modelState in ViewData.ModelState.Values)
                {
                    foreach (ModelError error in modelState.Errors)
                    {
                        if (!string.IsNullOrEmpty(error.ErrorMessage))
                            errMess = error.ErrorMessage;
                        else if (error.Exception != null)       // in case of binding error or bad request
                            errMess = error.Exception.Message;

                        if (errMess != "")
                            break;      // only want the first error message
                    }
                }

Was This Post Helpful? 1
  • +
  • -

#3 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 7085
  • View blog
  • Posts: 24,086
  • Joined: 05-May 12

Re: ModelState get friendly error message

Posted 04 October 2019 - 06:07 AM

So something like this:
var errorMessage = ViewData.ModelState
                           .Values
                           .SelectMany(modelState => modelState.Errors)
                           .Select(error => !string.IsNullOrEmpty(error.ErrorMessage)
                                            ? error.ErrorMessage
                                            : error.Exception?.Message)
                           .FirstOrDefault(message => !string.IsNullOrEmpty(message));


Was This Post Helpful? 1
  • +
  • -

Page 1 of 1