问题
I like to use the RenderAction
extension method on the HtmlHelper
object to render sidebars and the like in pages, as it allows me to keep the data access code for each such part in separate methods on the controller. Using an abstract controller base, I can define a default "sidebar strategy", which can then be refined by overriding the method in a concrete controller, when needed.
The only "problem" I have with this approach, is that the RenderAction
is built in a way where it always creates a news instance of the controller class, even when rendering actions from the controller already in action. Some of my controllers does some data lookup in their Initialize
method, and using the RenderAction
method in the view causes this to occur several times in the same request.
Is there some alternative to RenderAction
which will reuse the controller object if the action method to be invoked is on the same controller class as the "parent" action?
回答1:
You could call this.[ActionName] in your controller.
e.g this.Index() in the About action method of the home controller would cause the Index view to b e rendered without going through the controller initialisation once again. This will only workfor a whole page though.
A renderPartial would work for you but you would have to make sure the "elements" (sidebars etc) have all the data they need in the parent's view model.
e.g RenderPartial("SideBars", ViewData.Model). If your ViewModel contains everything you need for the partials, they can the be added top the Shared views and your controller need only set up the initial ViewMoel.
Kindness,
Dan
来源:https://stackoverflow.com/questions/1896497/like-html-renderaction-but-without-reinstantiating-the-controller-object