mvc3, can you give controller a display name?

2020-07-21 02:39发布

问题:

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"];
}

I expect to see "Facebook Employee", but its not working.

回答1:

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

Edit

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


回答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>