开发者

GUIs and Data Validation [MVC]

开发者 https://www.devze.com 2023-04-01 03:02 出处:网络
If a view contains invalid data, who is responsible for reporting to the controller that there exist invalid data? [Before persisting].

If a view contains invalid data, who is responsible for reporting to the controller that there exist invalid data? [Before persisting].

For example:

 Model:
  Name [must not be empty, and at least X characters]
  Age [must be an integer, greater than 0]
 View:
  Text box for the name [with some kind of indicator of being invalid]
  Text box for the age [with some kind of indicator of being invalid]

When the controller 开发者_运维百科is notified that the data entry is complete. [From the view] Which class is responsible for letting the controller know that the data is invalid? [Lets say that the user did not enter a name, and put in a non number for the age] I can see it being the model's responsibility because it is directly responsible for the data, and the context. However I can also see how it is the view's responsibility because it allows for the input of the invalid data in the first place.


The controller is responsible for the "logic" in an MVC triad, and deciding whether data is valid is definitely "logic", so it's actually the controller that should be responsible for deciding whether the data is valid. That said, it's not uncommon for the model to participate somewhat in this decision (e.g.: via validation attributes on its members or implementation of a validation helper interface).

The view should not participate at all in the decision of whether the data is valid since the view should not include any significant logic. The view might display information concerning validity of the model and/or its parts (e.g.: a "bad value" indicator next to a text box), but the decision to display this information should ultimately be made by the controller.


I would say the view should ask the model whether the input is valid. In the end, it is the model that controls the data.

0

精彩评论

暂无评论...
验证码 换一张
取 消