问题
ModelState.IsValid is returning false for me in my controller. I know that means one or more model errors were found when model binding. My question is how do I see the errors?
I noticed that my particular ModelState has 6 items in it. If I try to do any of these...
ModelState[0].Errors[0].ToString()
ModelState[0].Errors[0].ErrorMessage
ModelState[0].Value.AttemptedValue
I get this error:
The best overloaded method match for 'System.Web.Mvc.ModelStateDictionary.this[string]' has some invalid arguments
回答1:
The indexor into the ModelState is a string (usually the property name of the offending model or name of the html element).
If you check the MSDN docs for the ModelState class, you'll see that it has an Errors collection that will allow you to iterate over the error items (which are ModelError instances) to see what caused them.
回答2:
in controller;
ModelState.AddModelError("username", "Bad username");
in view;
<%= Html.ValidationMessage("username") %>
also
<%= Html.ValidationSummary() %>
Html.ValidationSummary() might be what you are looking for.
来源:https://stackoverflow.com/questions/1572289/asp-net-mvc-model-state