Asp.net mvc RenderAction RouteData Controller and Action values

不羁的心 提交于 2019-12-07 17:20:37

问题


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:


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.



来源:https://stackoverflow.com/questions/3953917/asp-net-mvc-renderaction-routedata-controller-and-action-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!