views:

106

answers:

1

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.

+1  A: 

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.
tvanfosson