什么时候应该使用 ASP.NET MVC 创建单独的控制器?
我开始学习 ASP.NET MVC。我理解控制器、模型和视图的概念。然而现在我开始设计我的第一个网站,我对应该创建什么控制器有点迷失。大多数模型对象都有相应的控制器吗?或者,在将操作方法分组到单独的控制器中时,我还应该考虑其他因素吗?
I'm starting to learn ASP.NET MVC. I understand the concept of controllers, models, and views. Yet now that I'm starting to design my first site I'm a little lost as to what controllers I should be creating. Do most model objects have a corresponding controller? Or are there other considerations I should be making when grouping action methods into seperate controllers?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
控制器在逻辑上分隔小的功能区域(不要与 MVC 中分隔较大功能部分的区域混淆)。
您是否有用于创建帐户、更改密码等内容的用户帐户管理?那是一个 UserAccountController。
你们有允许人们创建、查看、删除论坛帖子的功能吗?那是您的论坛控制器。
您是否具有允许人们管理其首选项的功能?这就是您的 PreferencesController。
与其说每个模型有 1 个控制器,不如说应用程序中的每个逻辑部分有 1 个控制器(通常确实是一个模型类)。一些重要的 MVC 站点仅使用一个控制器就可以正常工作,而我的上一个项目有八个控制器。
Controllers logically separate small areas of functionality (Not to be confused with Areas in MVC which separate larger functional sections).
Do you have User Account Management for stuff like CreateAccount, ChangePassword? That's a UserAccountController.
Do you have functionality that allows people to create, view, delete Forum Postings? That's your ForumController.
Do you have functionality that allows people to manage their Preferences? That's your PreferencesController.
It's not so much 1 Controller per Model, it's 1 Controller per logical section in your app (which often indeed is one Model class). Some non-trivial MVC Sites work fine with only one controller, while my last project had eight of them.
到目前为止,根据我有限的 MVC 经验,我的大多数控制器都对应于模型对象。我还认为您会为站点中的特定功能创建控制器,例如上传文件等。
In my limited experience with MVC so far, most of my controllers correspond to the model objects. I would also feel that you would create controllers for specific functionality within your site, like uploading files, etc.