关于MVC的简单问题
假设我有两个对象 A 和 B,它们都有模型、视图和控制器。用户位于 A 的视图中,然后按下按钮或其他东西来调用 A 控制器中的操作。此操作需要使用一些 B 模型。从 A 控制器中的操作,我应该直接调用 B 模型,还是应该通过 B 控制器与 B 模型交互?感谢您的阅读。
Let's say I have two objects, A and B, both with a model, view and a controller. The user is in the view for A, then presses a button or something that calls an action in the A controller. This action requires some use of the B model. From the action in the A controller, am I supposed to call directly to the B model, or should I be going through the B controller to interact with the B model? Thanks for reading.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以使用 ViewModel 模式,请参阅此 ASP.NET MVC ViewModel 模式
You can have a ViewModel pattern see this ASP.NET MVC ViewModel Pattern
我想你应该通过 B 控制器,因为 B 控制器可以访问 B 模型。
I guess you should go through the B controller as B controller has access to B model.
如果对象之间存在关系(例如,问题和答案之间存在多对多关系),则可以为对象 A 模型提供对象 B 模型的列表(反之亦然)
在对象的模型类中A,这看起来像:
对于对象 B(答案,它有一个 IList 问题)也类似。
这允许您在控制器中将对象 B(答案)作为
object.answers
调用,或者您有它结构化了。您可能需要添加多对多关系
OnModelBuild()
,如下所示:If the objects have a relation between them (for example, a many-to-many relation between question and answer), you can give your object A model a list of object B models (and vice-versa)
In your model class for object A, this would look like:
And similarly for object B (Answers, which has an IList of Questions)
This allows you to call Object B (Answer) in your Controller as
object.answers
or however you have it structured.You'll likely have to add the many-to-many relation
OnModelBuild()
like:你永远不应该从 A 调用 B 控制器,反之亦然,因为这样你就创建了一个过于严格的应用程序!您应该始终解耦您的应用程序。
想象一下,您更改了 A 控制器正在使用的控制器 B 的方法的工作方式,您将陷入困境。
更好的方法是创建另一个层来处理所有这些,控制器应该只调用这些层,
例如:
业务层(BLL):具有UserBLL.cs ->有一个方法:
验证(字符串用户名,字符串密码){}
您的控制器 A 和 B 都可以调用该层(UserBLL.cs)并利用它。这样应用程序将变得健壮且解耦。
最好创建另一个层,一个存储库层(用于 Crud 操作)。
You should never call B controller from A or vice verse, Cause in this way you are making an application that will be too strict ! You should always decouple your application.
Imagine you change the working for controllers B's method which was being used by A controller, you will be stuck.
A better way is to create another layer which handles all this and the controllers should just call the layers,
For ex:
Business Layer(BLL) : Having UserBLL.cs -> having a method :
Authenticate(string username,string password){}
Your Controller A and B both can call up this layer(UserBLL.cs) and utilize it.This way the application will be Robust and decoupled.
Better should create another layer,a Repository layer (For Crud operations ).
您可以创建一个包含两个模型的视图模型
,也可以将控制传递给处理 B 模型逻辑的控制器。
我能想到的最后一个场景是创建一个 B 服务,它获取 A 模型并执行逻辑
You can either create a viewmodel containing both models
Or you can pass the control to the controller that handles the B model logic.
The last scenario I can think of is creating a B Service which gets the A model and does the logic