views:

220

answers:

1

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?

A: 

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

Daniel Elliott
With `RenderPartial()` the view explicitly states which partial view to include in my sidebar, and the controller has to provide the data for this partial upfront. With `RenderAction()` the controller gets to decide what is going into the sidebar, and any data access required for the sidebar can be postponed until this decision is made. Both methods have use cases, but for what I am trying to do, I believe `RenderAction()` is best fit.
Jørn Schou-Rode