2

Hi I have a method in my controller and has the following code

if (ModelState.IsValid)

{

    IDataOperations ops = DataSession.GetDataOperations(null);
    List<Department> dept = new List<Department>();
    ops.Load(dept);
    ops.Commit();
    int deptId = dept[dept.Count - 1].Id + 1;
    Department department = new Department()
    {
      Id = deptId,
      CompanyId = deptModel.CompanyId,
      Active = deptModel.Active,
      Name = deptModel.Name
    };

    ops.Create(department);
    ops.Commit();
    return RedirectToAction("CompanyDepartment", "Task");
}

else

{
  //some code

Every time the page runs it always goes to the else part, meaning model-state is invalid. How do I check where the error in the page is, what code can I add to show where the error in the page is.

Thank you

Ann L.
  • 13,760
  • 5
  • 35
  • 66
Gotham Must Fall
  • 111
  • 3
  • 11

6 Answers6

4

You can go through the modelstate collection, by the following code, by debbuging through this, you will see, your code will go in to the for loop, and you can understand, what was the error.

#if DEBUG
       /// <summary> 
 /// Output the properties which are causing the issues when 
 /// the model is binding. 
 /// </summary>
  public static void ModelStateErrors (ModelStateDictionary modelState)
        {
            var errors = modelState.Where(a => a.Value.Errors.Count > 0)
                .Select(b => new { b.Key, b.Value.Errors })
                .ToArray();

            foreach (var modelStateErrors in errors)
            {
                 System.Diagnostics.Debug.WriteLine("...Errored When Binding.",                                  modelStateErrors.Key.ToString());

            }

        }
#endif
Hari Gillala
  • 11,736
  • 18
  • 70
  • 117
3

Very likely the problem is in a field in your model that isn't shown in the view. If you are performing validation, put a validation summary on the page. (Specify that field-level errors should NOT be suppressed.) That will show you all the errors including those that don't belong to a visible field.

Ann L.
  • 13,760
  • 5
  • 35
  • 66
1

You can check where the error is by doing the following.

var errors = ModelState.Values.SelectMany(v => v.Errors);
        if (ModelState.IsValid)
        {

        }
0

Last time i had a problem like this it was because something was null that shouldnt be.

Put a breakpoint in your code on the line where you say:

   if (modelState.IsValid)

You can find which part of the code has errors by drilling down into the modelState. You should be able to work it out from there.

Gaz Winter
  • 2,924
  • 2
  • 25
  • 47
0

Please see this image drill down model state 1)select value 2)drill down each member and look for error

please find image link and see @RBT

Community
  • 1
  • 1
-3

Generate the field automatically when create view and copy the required fields then make some of them hidden as you want