mvc3,你能给控制器一个显示名称吗?

时间:2013-10-16 19:50:43

标签: asp.net-mvc asp.net-mvc-3 asp.net-mvc-4

我正在使用mvc3。是否可以为控制器和操作提供显示名称。

[DisplayName("Facebook Employee")]
public class EmployeeController : Controller

在我的痕迹中,我将获得控制器名称和操作名称

@{
var controllerName = ViewContext.RouteData.Values["Controller"];
var actionName = ViewContext.RouteData.Values["Action"];
}

我希望看到“Facebook员工”,但它不起作用。

2 个答案:

答案 0 :(得分:5)

您必须使用GetCustomAttributes反映Controller类型本身。使用ViewContext.Controller获取对控制器本身的引用。像这样:

string controllerName;
Type type = ViewContext.Controller.GetType();
var atts = type.GetCustomAttributes(typeof(DisplayNameAttribute), false);
if (atts.Length > 0)
    controllerName = ((DisplayNameAttribute)atts[0]).DisplayName;
else 
    controllerName = type.Name;   // fallback to the type name of the controller

修改

要对某个操作执行类似操作,您需要先使用Type.GetMethodInfo反映该方法:

string actionName = ViewContext.RouteData.Values["Action"]
MethodInfo method = type.GetMethod(actionName);
var atts = method.GetCustomAttributes(typeof(DisplayNameAttribute), false);
// etc, same as above

答案 1 :(得分:0)

Array ( [0] => bread [1] => 10 [2] => slices [3] => 25/12/2017 ) 

Array ( [0] => cheese [1] => 10 [2] => slices [3] => 25/12/2017 )