MVC - How can I hook to a controller action in order to change the view before it is being returned to the browser?
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.
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
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.
精彩评论