简体   繁体   English

MVC验证问题

[英]MVC validation question

I have just starting learning the MVC pattern today (for gui applications, not web), and have a few questions on where data validation should take place. 我今天才刚刚开始学习MVC模式(针对gui应用程序,而不是Web),并且对应该在哪里进行数据验证有一些疑问。

From what i have read, it seems like most people are saying that all the validations should take place on the controller, and the model should pretty much only hold the state of the data. 根据我的阅读,似乎大多数人都在说所有验证都应该在控制器上进行,并且模型应该只保留数据的状态。 However, it seems like in some situations it would make more sense to do the verification in the model. 但是,似乎在某些情况下,在模型中进行验证会更有意义。

For example, lets say that a client changes the ipv4 address of the server they want to connect to from the gui. 例如,假设客户端从gui更改了要连接的服务器的ipv4地址。 We want to verify that this is in fact an ipv4 address, and not just random characters. 我们要验证这实际上是ipv4地址,而不仅仅是随机字符。 If the ip address is valid, then we want to change that data in the model to the new ip address, and if it isn't valid we want to have the view display an error (or something). 如果IP地址有效,那么我们想将模型中的数据更改为新的IP地址,如果无效,我们希望视图显示错误(或其他内容)。

If you did the verification in the controller, then if in the future you decided you wanted to have a different controller/view (because from what i can tell, they are coupled pretty closely together), you would have to make sure to include this same verification code in both controllers, and would thus have to manage two pieces of the same code. 如果您在控制器中进行了验证,那么如果将来您决定要使用其他控制器/视图(因为据我所知,它们之间紧密耦合在一起),则必须确保将其包括在内两个控制器中使用相同的验证代码,因此必须管理两个相同的代码。 That would of course be more prone to bugs then managing just one piece of code, like if the verification was done in the model. 当然,如果只对一段代码进行管理,那将更容易产生错误,就像验证是在模型中完成一样。

Should i be doing it this way? 我应该这样吗? Or am i missing that makes doing it in the controller make more sense? 还是我错过了使它在控制器中更有意义的事情? Or should some data be handled in the model, and some data handled in the controller? 还是应该在模型中处理一些数据,而在控制器中处理一些数据?

Thanks 谢谢

I guess that at the model the verification is always necessary. 我想在模型上验证总是必要的。 Some times would be nice to have also in the view so that the user would be event not allowed to input something other than what the field is asking for. 有时在视图中也很高兴,这样事件将不允许用户输入除字段要求之外的内容。 One way or the other, generic verification like IP addresses validation make's a great candidate to be a global/static/utility method to be used, not only in the view and in the model but in several different models. 诸如IP地址验证之类的通用验证以一种方式或其他方式成为了要使用的全局/静态/实用方法的最佳选择,不仅在视图和模型中,而且在几种不同的模型中。 Sometimes it can even be shared between client's view components and server components like in a GWT application 有时甚至可以像GWT应用程序一样在客户端的视图组件和服务器组件之间共享它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM