ASP.NET MVC RenderAction RouteData控制器和操作值 [英] Asp.net mvc RenderAction RouteData Controller and Action values

查看:131
本文介绍了ASP.NET MVC RenderAction RouteData控制器和操作值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在母版"页面上创建一个RenderAction方法,该方法将根据当前控制器和操作动态生成侧边栏.在视图中调用RenderAction时,将使用该特定RenderAction方法的控制器和操作进行填充.例如,如果我在主页"的控制器上,并且在索引"的操作上,则我期望GenerateSideBar方法中的主页"和索引".相反,我得到了"Home"的控制器和"RenderSideBar"的动作.谢谢您的帮助!

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!

我的母版页浏览:

   <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 }); %>

控制器操作:

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

            return null; 
        }

推荐答案

问题在于控制器和操作参数名称很特殊,因为它们在路由中使用,并且在默认模型绑定程序尝试设置其值时会优先使用.只需像这样重命名它们:

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)
{
    ...
}

并渲染它:

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

现在,您应该获得正确的父操作名称.另外,如果此操作仅打算用作子操作,则可以使用 [ChildActionOnly] 属性.

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.

这篇关于ASP.NET MVC RenderAction RouteData控制器和操作值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆