【问题标题】:mvc3, can you give controller a display name?mvc3,你能给控制器一个显示名称吗?
【发布时间】:2013-10-16 19:50:43
【问题描述】:

我正在使用 mvc3。是否可以给控制器和动作一个显示名称。

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

在我的面包屑中,我将获得控制器名称和动作名称

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

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

【问题讨论】:

  • 你为什么只设置一个标题?并在视图中调用标题

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


【解决方案1】:

您必须使用GetCustomAttributes 反映控制器类型本身。使用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

【讨论】:

  • 非常感谢,它尝试做同样的事情来获取动作显示名称。 ViewContext.Action.GetType(),它不起作用。我如何获得当前的动作类型?
  • @feelexit 对于 Action 来说略有不同——请参阅上面的更新。
【解决方案2】:
     public static class HLP
      {

  public static string DisplayNameController(this WebViewPage wvp)
    {
        if (wvp.ViewBag.Title != null && (wvp.ViewBag.Title as string).Trim().Length > 0)
            return wvp.ViewBag.Title;

        ControllerBase Controller = wvp.ViewContext.Controller;
        try
        {
            DisplayNameAttribute[] attr = (DisplayNameAttribute[])Controller.GetType().GetCustomAttributes(typeof(DisplayNameAttribute), false);
            string DisplayName = attr[0].DisplayName; 

            return DisplayName;
        }
        catch (Exception)
        {
            return Controller.ToString();
        }
    }

    public static string DisplayNameAction(this WebViewPage wvp)
    {
        string actionName = wvp.ViewContext.RouteData.Values["Action"].ToString();

        try
        {
            Type type = wvp.ViewContext.Controller.GetType();
            MethodInfo method = type.GetMethod(actionName); 

            DisplayNameAttribute[] attr = (DisplayNameAttribute[])method.GetCustomAttributes(typeof(DisplayNameAttribute), false);
            string DisplayName = attr[0].DisplayName; 
            return DisplayName;
        }
        catch (Exception)
        {
            return actionName;
        }

    }
}



 <title>@this.DisplayNameAction()</title>

【讨论】:

    猜你喜欢
    • 2014-08-16
    • 2017-04-10
    • 1970-01-01
    • 1970-01-01
    • 2019-12-22
    • 2010-11-15
    • 2016-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多