C# .NET MVC3 ModelState.IsValid

前端 未结 3 530
一个人的身影
一个人的身影 2021-02-01 09:23

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 d

相关标签:
3条回答
  • 2021-02-01 09:40

    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.

    0 讨论(0)
  • 2021-02-01 09:51

    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);
                    }
                } 
    
    0 讨论(0)
  • 2021-02-01 09:58

    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;
    
    0 讨论(0)
提交回复
热议问题