[英]How do I pass data from a controller to a strongly typed user control in asp.net mvc?
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? 如何在母版页中告诉UserControl应该从特定的Controller / Controller Action获取其数据? I'd like to access the viewdata within the ascx just as I would in a normal View. 我想像在普通View中一样在ascx中访问viewdata。
Pass model and ViewData as parameters to the RenderPartial method. 将模型和ViewData作为参数传递给RenderPartial方法。 It will make model and view data accessible as if you were in the parent view page. 它将像访问父视图页面一样使模型和视图数据可访问。
<% Html.RenderPartial ( "../Shared/HRMasterData/DependentPersonDossiers",
ViewData.Model, ViewData ); %>
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. 在基本控制器中重写OnActionExecuted,然后检查结果是否为ViewResult。 If it is, find the orders and add them to the ViewData. 如果是这样,找到订单并将其添加到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. 重用(调用)OrdersController中基本控制器中的代码,以执行呈现订单视图的操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.