ASP.NET MVC Model State

怎甘沉沦 提交于 2020-01-04 02:20:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!