Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# .NET MVC3 ModelState.IsValid

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

like image 459
z.eljayyo Avatar asked Apr 01 '11 08:04

z.eljayyo


1 Answers

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.

like image 69
Darin Dimitrov Avatar answered Oct 27 '22 04:10

Darin Dimitrov