Like Html.RenderAction() but without reinstantiating the controller object

孤街醉人 提交于 2019-12-07 02:00:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!