在MVC视图中获取当前控制器动作的属性

在MVC视图中获取当前控制器动作的属性

问题描述:

我希望以易于阅读的格式在MVC视图上显示控制器的当前动作.

I wish to display the current action of the controller on my MVC View in a human readable format.

我了解您可以通过以下方式获取当前操作的名称:
@ ViewContext.Controller.ValueProvider.GetValue("action")
这将返回例如下例中的索引"

I understand you can acquire the name of the current action through:
@ViewContext.Controller.ValueProvider.GetValue("action")
this returns e.g. 'Index' in the example below

我想要做的事情是这样的:

What I am looking to do is something like:

[DisplayName=Resources.Overview]
public ActionResult Index()
{
    return View();
}

,然后在页面上打印该DisplayName,例如:p

and then print that DisplayName on the page, some pseudo-code like:

@ ViewContext.Controller.ValueProvider.GetValue("action").GetAttribute("DisplayName")
将从资源返回概述"

@ViewContext.Controller.ValueProvider.GetValue("action").GetAttribute("DisplayName")
which would return 'Overview' from Resources

这可能吗?

您应该首先使用 Type.GetMethodInfo

string actionName = ViewContext.RouteData.Values["Action"]
MethodInfo method = type.GetMethod(actionName);
var attribute = method.GetCustomAttributes(typeof(DisplayNameAttribute), false);
if (attribute.Length > 0)
   actionName = ((DisplayNameAttribute)attribute[0]).DisplayName;
else 
   actionName = type.Name;   // fallback to the type name of the controller

然后您可以使用类似

   ViewBag.name = actionName;

然后从视图中获取Viewbag变量

and then get the Viewbag variable from the view