Why does MVC use the Modelstate over a supplied Model on a GET

只愿长相守 提交于 2019-12-05 09:23:50

The DefaultModelBinder does not make a distinction between GET and POST requests. While only the MVC team can confirm why they made that decision, there are valid use cases why ModelState should be used in a GET (in the same way its used in a POST) since you can also submit a form to a GET method.

Take for example an airline booking app, where you have a model with properties to select departure and arrival locations, a date, and the number of passengers (an int property), plus a collection property for the filtered results. The GET method signature might look like

public ActionResult Search(SearchViewModel model)

The view includes a that makes a GET back to the method and includes a textbox for the number of passengers.

A (not too bright) user who has disabled javascript enters "TWO" in the textbox and submits the form. Your method returns the view without populating the collection of available flights because ModelState is invalid (the value "TWO" is not valid for an int) and now the user sees an error message stating The field Passengers must be a number.

If the model value was used rather that the ModelState value, then the associated textbox would be displaying 0 instead of "Two", making the error message confusing (but 0 is a number! - and what happened to what I entered?)

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