0

ModelState.IsValid is always returning false in my edit form. It doesn't even hit the try catch. What am I doing wrong?

[AcceptVerbs("POST", "PUT")]
       public ActionResult Edit(ItemModel model)
       {   
               int customerID = model.customerID;

               using (BusinessLogicLayer BLL = new BusinessLogicLayer())
               {

               if (ModelState.IsValid)
               {

                   try
                   {   
                       BLL.InsertData(model.customerID);
                       BLL.SaveChanges();
                   }
                   catch (Exception e)
                   {
                      return View();
                   }
               }
           }

           return View();
       } 
coffeetime
  • 121
  • 2
  • 6
  • 14
  • 1
    If `ModelState` is invalid, then the values you are posting from the form are not valid fro the properties of your model. You have not shown either the model or the view so we cannot answer this, but you can insect `ModelState` to determine the Keys (property names) and associated errors (or use `var errors = ModelState.Keys.Where(k => ModelState[k].Errors.Count > 0).Select(k => new { propertyName = k, errorMessage = ModelState[k].Errors[0].ErrorMessage });`) –  Nov 09 '18 at 20:42

1 Answers1

0

What the code says. Model is not valid. That could be anything in regards to the model you are passing though the endpoint. Perhaps ItemModel has a [Required] attribute on one of its properties and you are trying to pass a NULL value on that property.

Also, as per the comment from Stephen Muecke: You can inspect ModelState to determine the Keys (property names) and associated errors by accessing the Keys property of the ModelState like so

var errors = ModelState.Keys
                   .Where(k => ModelState[k].Errors.Count > 0)
                   .Select(k => new 
                   { 
                       propertyName = k, 
                       errorMessage = ModelState[k].Errors[0].ErrorMessage 
                   }).ToList()
qubits
  • 1,227
  • 3
  • 20
  • 50