gpt4 book ai didi

asp.net-mvc - 像 Html.RenderAction() 但没有重新实例化 Controller 对象

转载 作者:行者123 更新时间:2023-12-04 16:03:09 24 4
gpt4 key购买 nike

我喜欢用 RenderAction HtmlHelper上的扩展方法对象在页面中呈现侧边栏等,因为它允许我将每个此类部分的数据访问代码保留在 Controller 上的单独方法中。使用抽象 Controller 基础,我可以定义默认的“侧边栏策略”,然后可以在需要时通过覆盖具体 Controller 中的方法来改进。

我对这种方法的唯一“问题”是 RenderAction以一种始终创建 Controller 类的新闻实例的方式构建,即使在渲染来自 Controller 的 Action 时也是如此。我的一些 Controller 在他们的 Initialize 中进行了一些数据查找。方法,并使用 RenderAction View 中的方法导致这种情况在同一个请求中发生多次。
RenderAction有什么替代品吗?如果要调用的操作方法与“父”操作在同一个 Controller 类上,哪个将重用 Controller 对象?

最佳答案

您可以在 Controller 中调用 this.[ActionName]。

例如 home Controller 的 About action 方法中的 this.Index() 将导致 Index View 被渲染,而无需再次通过 Controller 初始化。不过,这只适用于整个页面。

renderPartial 对您有用,但您必须确保“元素”(侧边栏等)在父 View 模型中具有他们需要的所有数据。

例如 RenderPartial("SideBars", ViewData.Model)。如果您的 ViewModel 包含您需要的所有部件,它们可以添加到共享 View 的顶部,并且您的 Controller 只需要设置初始 ViewMoel。

善良,

关于asp.net-mvc - 像 Html.RenderAction() 但没有重新实例化 Controller 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1896497/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com