像Html.RenderAction()一样,但是没有重新实例化控制器对象 [英] Like Html.RenderAction() but without reinstantiating the controller object

查看:108
本文介绍了像Html.RenderAction()一样,但是没有重新实例化控制器对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢在HtmlHelper对象上使用RenderAction扩展方法来渲染页面中的侧边栏等,因为它允许我将每个此类部件的数据访问代码保留在控制器上的单独方法中.使用抽象控制器库,我可以定义一个默认的侧边栏策略",然后可以通过在需要时在具体控制器中覆盖该方法来对其进行完善.

我使用这种方法的唯一问题"是,RenderAction的构建方式始终是创建控制器类的新闻实例,即使从已在起作用的控制器中渲染动作也是如此.我的某些控制器在其Initialize方法中进行了一些数据查找,并且在视图中使用RenderAction方法导致在同一请求中多次发生这种情况.

RenderAction是否有替代方法,如果要调用的操作方法与父"操作在同一控制器类上,则该方法将重用控制器对象?

解决方案

您可以在控制器中调用此名称.[ActionName].

例如,家用控制器的About操作方法中的this.Index()会导致索引视图被渲染,而无需再次进行控制器初始化.不过,这仅适用于整个页面.

renderPartial可以为您工作,但您必须确保元素"(侧边栏等)具有父级视图模型中所需的所有数据.

例如RenderPartial("SideBars",ViewData.Model).如果您的ViewModel包含了部分对象所需的所有内容,则可以将它们添加到共享"视图的顶部,并且您的控制器只需设置初始ViewMoel.

仁慈

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?

解决方案

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

这篇关于像Html.RenderAction()一样,但是没有重新实例化控制器对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆