asp.net-mvc 获取 ControllerName 和 ActionName 并在 Master Page 中填充 ViewData?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1212429/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-07 23:45:01  来源:igfitidea点击:

Get ControllerName and ActionName and populate the ViewData in Master Page?

asp.net-mvcmaster-pages

提问by Abdulsattar Mohammed

I've a SuperControllerwhich will be inherited from all the controllers. In the constructor I'm trying to populate the ViewData usingthe ControllerName and the ActionName.

我有一个SuperController将从所有控制器继承的。在构造函数中,我尝试使用ControllerName 和 ActionName填充 ViewData 。

I'm not going to pass the ControllerName and the ActionName as the ViewData. I've a method that needs the ControllerName and the ActionName and I need to pass the return value of the method as the ViewData.

我不会将 ControllerName 和 ActionName 作为 ViewData 传递。我有一个需要 ControllerName 和 ActionName 的方法,我需要将该方法的返回值作为 ViewData 传递。

How can I do that?

我怎样才能做到这一点?

回答by eu-ge-ne

Don't use ViewData. Use this in your Site.Master instead:

不要使用ViewData. 在您的 Site.Master 中使用它:

<%= ViewContext.RouteData.Values["Controller"] %>
<%= ViewContext.RouteData.Values["Action"] %>

SO - Getting the name of the controller and action method in the view in ASP.Net MVC

SO - 在 ASP.Net MVC 的视图中获取控制器和操作方法的名称

回答by José Silva

Try this:

尝试这个:

RouteData.Values.First().Value.ToString()

回答by James S

Assuming that I'm reading your post correctly, and you're not trying to access the controller/action names in the view, but INSTEAD trying to do something with them, and put the result into the viewdata:

假设我正确阅读了您的帖子,并且您没有尝试访问视图中的控制器/操作名称,而是尝试对它们执行某些操作,并将结果放入视图数据中:

You can't do it in the constructor because the context hasn't been created yet. You need to override the Initialize method:

您不能在构造函数中执行此操作,因为尚未创建上下文。您需要覆盖 Initialize 方法:

protected override void Initialize(System.Web.Routing.RequestContext requestContext)
    {
        base.Initialize(requestContext);

        //here the routedata is available
        ViewData["controller_name"] = (ControllerContext.RouteData.Values["Controller"];
    }

(Note that you could pass in just the ControllerContext.RouteData to your function and let it pick the values it needs.)

(请注意,您可以仅将 ControllerContext.RouteData 传递给您的函数,并让它选择所需的值。)

回答by Wyatt Barnett

I needed to get at these alot from views, and I hit it from a slightly different angle--I wrote a few extension methods to HtmlHelper to give the current ControllerName and ActionName. A bit easier to handle as you don't need to worry about diving into the ViewData[] bag or injecting stuff at appropriate places.

我需要从视图中获取很多信息,并且我从一个稍微不同的角度进行分析——我为 HtmlHelper 编写了一些扩展方法来提供当前的 ControllerName 和 ActionName。更容易处理,因为您无需担心潜入 ViewData[] 包或在适当的位置注入东西。