如何将数据从控制器传递到asp.net mvc中的强类型用户控件?

时间:2021-07-09 16:48:21

I have a strongly typed User Control which should show a user's orders on all pages, it's included in a master page. I have an OrdersController which can give me the current orders and is used at other locations.

我有一个强类型的用户控件,它应该在所有页面上显示用户的订单,它包含在母版页中。我有一个OrdersController,可以给我当前的订单,并在其他地方使用。

How do I tell the UserControl in the Master Page that it should get its Data from that specific Controller / Controller Action? I'd like to access the viewdata within the ascx just as I would in a normal View.

如何告诉母版页中的UserControl它应该从该特定的控制器/控制器动作获取其数据?我想像在普通视图中一样访问ascx中的viewdata。

2 个解决方案

#1


Pass model and ViewData as parameters to the RenderPartial method. It will make model and view data accessible as if you were in the parent view page.

将模型和ViewData作为参数传递给RenderPartial方法。它将使模型和视图数据可访问,就像您在父视图页面中一样。

<% Html.RenderPartial ( "../Shared/HRMasterData/DependentPersonDossiers",
  ViewData.Model, ViewData ); %>

#2


One way to do this would be to implement a base controller. Move the logic that obtains the orders to the base controller. Override OnActionExecuted in the base controller and check if the result is a ViewResult. If it is, find the orders and add them to the ViewData. In your master, check if the orders are present in the view data and, if so, render them. If not, show an "order data unavailable" message (this latter shouldn't happen, but it's best to be safe). Reuse (call) the code in the base controller in your OrdersController for the action that renders the orders view.

一种方法是实现基本控制器。将获取订单的逻辑移动到基本控制器。覆盖基本控制器中的OnActionExecuted并检查结果是否为ViewResult。如果是,请查找订单并将其添加到ViewData。在您的主数据库中,检查视图数据中是否存在订单,如果是,则进行渲染。如果没有,则显示“订单数据不可用”消息(后者不应该发生,但最好是安全的)。重复(调用)OrdersController中基本控制器中的代码,以获取呈现订单视图的操作。

#1


Pass model and ViewData as parameters to the RenderPartial method. It will make model and view data accessible as if you were in the parent view page.

将模型和ViewData作为参数传递给RenderPartial方法。它将使模型和视图数据可访问,就像您在父视图页面中一样。

<% Html.RenderPartial ( "../Shared/HRMasterData/DependentPersonDossiers",
  ViewData.Model, ViewData ); %>

#2


One way to do this would be to implement a base controller. Move the logic that obtains the orders to the base controller. Override OnActionExecuted in the base controller and check if the result is a ViewResult. If it is, find the orders and add them to the ViewData. In your master, check if the orders are present in the view data and, if so, render them. If not, show an "order data unavailable" message (this latter shouldn't happen, but it's best to be safe). Reuse (call) the code in the base controller in your OrdersController for the action that renders the orders view.

一种方法是实现基本控制器。将获取订单的逻辑移动到基本控制器。覆盖基本控制器中的OnActionExecuted并检查结果是否为ViewResult。如果是,请查找订单并将其添加到ViewData。在您的主数据库中,检查视图数据中是否存在订单,如果是,则进行渲染。如果没有,则显示“订单数据不可用”消息(后者不应该发生,但最好是安全的)。重复(调用)OrdersController中基本控制器中的代码,以获取呈现订单视图的操作。