MVC - 如何挂钩控制器操作以便在视图返回到浏览器之前更改视图?
我对 MVC 有点陌生,所以如果我在这里问一些奇怪的问题,我很抱歉。 基本上,我试图以可插入的方式修改现有的电子商务 MVC 应用程序,这意味着我不想触及现有代码,而是引用应用程序的相关程序集并使用应用程序中的所有扩展点。
有一个 CategoryView
显示给定类别中的所有产品。我想以某种方式连接到控制器或模型或视图,以便更改此 CategoryView
模型中的一些数据。
我能想到的唯一方法是更改视图的路由并编写我自己的控制器和操作。在我的操作中,我可以调用原始控制器和操作来获取 ViewResult 并在将其返回到 ViewEngine 之前对其进行操作。 从表面上看,这对我来说似乎是错误的,而且我不确定是否可以从我的控制器的操作中调用另一个控制器的操作。
所以我想知道从 MVC 的角度来看,是否有一种方法可以连接到 CategoryView 控制器、模型或操作,以便更改视图中显示的数据?我是从 MVC 的角度说的,因为否则应用程序中没有预定义的自定义扩展点来执行此操作。
请指教。
I am a bit new to MVC so apologies if I am asking something strange here.
Basically I am trying to modify an existing e-commerce MVC application but in a pluggable way, meaning that I do not want to touch the existing code but rather reference the relevant assemblies of the application and use all the extension points in the application.
There is a CategoryView
that shows all the products in a given category. I would like somehow to hook into the controller or the model or the view, in order to change some of that data in the model for this CategoryView
.
The only way I could think of to do that is to change to route for the view and write my own controller and action. And in my action I can call the original controller and action to get the ViewResult
and manipulate it before returning it to the ViewEngine
.
On the face of it this seems wrong to me and moreover I am not sure whether I can call another controller's action from my controller's action.
So I was wondering whether from and MVC point of view there is at all a way to hook into the CategoryView
controller, model or action in order to change the data that is being shown in the view? I am saying from an MVC point of view because otherwise there are no predefined custom extension points in the application to do that.
Please advise.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以通过 ActionFilter 来完成此操作,或者在控制器中调用 RenderView() 然后修改结果。
请参阅:在视图中使用操作过滤器
You can do this via an ActionFilter or in your controller you can call RenderView() and then modify the result.
See: Using Action Filter with view
查看 ActionFilterAttribute。这允许您在调用操作之前或之后以及执行该操作返回的 ActionResult 之前和之后挂钩执行代码。
此类的每个方法都接收一个上下文对象。上下文对象有一个可以操作的 Result 属性。
Take a look at the ActionFilterAttribute. This allows you to hook into executing code just before or after an action is called and just before and after the ActionResult returned by the action is executed.
Each of the methods of this class receive a context object. The context object has a Result property that you can manipulate.