views:

12

answers:

1

I am trying to create a RenderAction method on the Master page that will dynamically generate a side bar based on the current controller and action. When the RenderAction is called in the view it is populated with the controller and action of that particular RenderAction Method. For Example, if I am on the controller of “Home” and action of “Index” I am expecting "Home" and "Index" in the GenerateSideBar method. Instead I get the controller of “Home” and action of “RenderSideBar”. Thanks For your Help!

My Master Page View:

   <div class="side-bucket">
    <%
        string Controller = ViewContext.RouteData.Values["Controller"].ToString();
        string Action = ViewContext.RouteData.Values["Action"].ToString();
    %>
    <% Html.RenderAction("RenderSideBar", "Home", new { controller = Controller, action = Action }); %>

Controller Action:

public ActionResult GenerateSideBar(string controller, string action)
        {
            switch (controller.Trim().ToLower())
            {
                case "member" :
                    return View(@"sidebar\MemberSidebar");
                default:
                    break;
            }

            return null; 
        }
+1  A: 

The problem is that controller and action parameter names are special because used in your routes and will take precedence when the default model binder tries to set their values. Simply rename them like this:

public ActionResult GenerateSideBar(string currentController, string currentAction)
{
    ...
}

and render it:

<% Html.RenderAction("RenderSideBar", "Home", 
    new { currentController = ViewContext.RouteData.Values["controller"], 
          currentAction = ViewContext.RouteData.Values["action"] }
); %>

Now you should get the correct parent action name. Also if this action is intended to be used only as child action you could decorate it with the [ChildActionOnly] attribute.

Darin Dimitrov
that worked! Thanks for your help Darin!
Zaffiro