12

Im using JSON to post data from a form and ModelState.isValid() returning false, i put a WriteLine for all incoming data and everything looks fine data wise, is there a way to display model state errors to figure out what is not validating? this exact code works fine with other models

[HttpPost]
public ActionResult mobileCreateAction(Trip trip)
{
    if (ModelState.IsValid)
    {
        System.Diagnostics.Debug.WriteLine("saving");
        DB.Trips.Add(trip);
        DB.SaveChanges();
        return Json(new
        {
            success = true,
            msg = "Success saving trip"
        });
    }
    else
    {
        System.Diagnostics.Debug.WriteLine("invalid model state");
        return Json(new
        {
            success = false,
            msg = "Error saving trip"
        }, JsonRequestBehavior.AllowGet);
    }  
}

thanks

Frank
  • 2,015
  • 10
  • 36
  • 57
z.eljayyo
  • 1,289
  • 1
  • 10
  • 16

3 Answers3

34

To get a list of errors in the model state:

var errors = ModelState
    .Where(x => x.Value.Errors.Count > 0)
    .Select(x => new { x.Key, x.Value.Errors })
    .ToArray();

Then put a break point on this line and inspect the errors variable. It will give you a list of properties on your model with their respective errors.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Darin when i print errors im getting this value: <>f__AnonymousType1`2[System.String,System.Web.Mvc.ModelErrorCollection], any idea what it means? – z.eljayyo Apr 03 '11 at 23:06
  • That line outputs an array of anonymous objects with two properties (Key and Errors). Try accessing those properties ans print that. – Megacan Jul 18 '12 at 12:15
2

You can find the errors in the ModelState.Values collection. Every value has an Errors collection that contains all the model errors for that property.

var errors = from v in ModelState.Values 
             where v.Errors.Count > 0 
             select v.Errors;
Freek Buurman
  • 1,279
  • 1
  • 9
  • 15
0

SO Post

Building on @Darin's answer the post linked above provides the code needed to display the 'why' message.

 foreach (var obj in ModelState.Values)
            {
                foreach (var error in obj.Errors)
                {
                    if (!string.IsNullOrEmpty(error.ErrorMessage))
                        System.Diagnostics.Debug.WriteLine("ERROR WHY = " + error.ErrorMessage);
                }
            } 
Community
  • 1
  • 1
John M
  • 14,338
  • 29
  • 91
  • 143