将 ViewData 传递给使用 Html.Action 返回的 PartialView

发布于 2024-08-31 05:55:53 字数 534 浏览 1 评论 0原文

我想通过从操作方法返回部分视图来将其嵌入到 ASP.NET MVC 页面中。

在我的基本视图中,我会:

<%= Html.Action("MyPartialViewAction") %>

我的控制器将有一个操作方法,例如:

[ChildActionOnly]
public ActionResult MyPartialViewAction()
{
    return PartialView("MyPartialView");
}

我希望返回的部分视图(MyPartialView)能够访问在基本页面的控制器操作中设置的ViewData,但这似乎不是案件。如果我通过在基本视图中使用以下内容插入部分视图,它会起作用:

<% Html.RenderPartial("MyPartialView") %>

但我不想这样做,因为我希望我的“MyPartialViewAction”执行逻辑来确定要返回哪个部分视图。

I want to embed a partial view in an ASP.NET MVC page by returning it from an action method.

In my base view, I would have:

<%= Html.Action("MyPartialViewAction") %>

My controller would have an action method like:

[ChildActionOnly]
public ActionResult MyPartialViewAction()
{
    return PartialView("MyPartialView");
}

I expected the returned partial view (MyPartialView) to have access to the ViewData that was set in the base page's controller action but that doesn't appear to be the case. If I insert the partial view by using the following in my base view it works:

<% Html.RenderPartial("MyPartialView") %>

I don't want to do that though because I want my "MyPartialViewAction" to execute logic to determine WHICH partial view to return.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

℡Ms空城旧梦 2024-09-07 05:55:53

我相信它实际上创建了一个新的控制器,这意味着它创建的任何视图都将具有来自该控制器的 ViewData,而不是创建调用 Action 方法的视图的控制器。您可能想尝试:

  1. 将选择逻辑重构为单独的方法,并在原始操作中使用它来选择部分视图名称。将其填充到您的模型中并通过 RenderPartial 使用它。
  2. 使用 TempData(或直接使用 Session)保存前一个操作的 ViewData 并从中合并新控制器的 ViewData。
  3. 如果所需的数据有限,请将其传递到 RouteValueDictionary 中——您的操作需要接收这些数据作为参数。

I believe that it actually creates a new controller, meaning that any view that it creates will have the ViewData from that controller, not the controller that created the view that is invoking the Action method. You might want to try:

  1. Refactor your selection logic to a separate method and use it in your original action to choose the partial view name. Populate that in your model and use it via RenderPartial.
  2. Use TempData (or Session, directly) to hold the previous action's ViewData and hydrate the new controller's ViewData from it.
  3. If the data required is limited, pass it in the RouteValueDictionary -- your action would need to receive these as parameters.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文