hokkaido
hokkaido

Reputation:

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.

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.

Upvotes: 0

Views: 223

Answers (2)

baretta
baretta

Reputation: 7585

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.

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

Upvotes: 1

tvanfosson
tvanfosson

Reputation: 532445

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.

Upvotes: 0

Related Questions