本文介绍了mvc3,可以给控制器显示名称吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用mvc3.是否可以给控制器和动作一个显示名称.
I am using mvc3. is it possible to give controller and action a display name.
[DisplayName("Facebook Employee")]
public class EmployeeController : Controller
在我的面包屑中,我将获得控制器名称和操作名称
in my breadcrumb, I will get the controller name and action name
@{
var controllerName = ViewContext.RouteData.Values["Controller"];
var actionName = ViewContext.RouteData.Values["Action"];
}
我希望看到"Facebook雇员",但是它不起作用.
I expect to see "Facebook Employee", but its not working.
推荐答案
您必须使用 GetCustomAttributes
.使用ViewContext.Controller
获取对控制器本身的引用.像这样:
You'll have to reflect on the Controller type itself, using GetCustomAttributes
. Use ViewContext.Controller
to get a reference to the controller itself. Something like this:
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
反思该方法:
To do similar for an action, you need to first reflect on the method, using Type.GetMethodInfo
:
string actionName = ViewContext.RouteData.Values["Action"]
MethodInfo method = type.GetMethod(actionName);
var atts = method.GetCustomAttributes(typeof(DisplayNameAttribute), false);
// etc, same as above
这篇关于mvc3,可以给控制器显示名称吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!