在MVC视图中获取当前控制器动作的属性 [英] Get attribute of current controller action in MVC View

查看:113
本文介绍了在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

这篇关于在MVC视图中获取当前控制器动作的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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