10

My goal is to create a custom attribute like System.ComponentModel.DataAnnotations.Display which allows me to pass a parameter.

Ex.: In System.ComponentModel.DataAnnotations.Display I can pass a value to the parameter Name

[Display(Name = "PropertyName")]
public int Property { get; set; }

I want to do the same but in controllers and actions like below

[CustomDisplay(Name = "Controller name")]
public class HomeController : Controller

and then fill a ViewBag or ViewData item with its value.

How can I do this?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Márcio Gonzalez
  • 1,020
  • 1
  • 8
  • 20
  • 1
    You have to reflect on the Controller type , using [`GetCustomAttributes`](https://msdn.microsoft.com/en-us/library/dwc6ew1d.aspx) use `ViewContext.Controller` Refer [this](http://stackoverflow.com/questions/19412483/mvc3-can-you-give-controller-a-display-name) – Divyang Desai Sep 29 '16 at 12:36
  • CustomAttributes not allow store data in ViewBag Or ViewData – Sandip - Frontend Developer Sep 29 '16 at 12:37
  • 1
    Refer [this answer](http://stackoverflow.com/questions/2656189/how-do-i-read-an-attribute-on-a-class-at-runtime) and then assign the result to `ViewBag` –  Sep 29 '16 at 12:39

1 Answers1

15

This is very simple

public class ControllerDisplayNameAttribute : ActionFilterAttribute
{
    public string Name { get; set; }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        string name = Name;
        if (string.IsNullOrEmpty(name))
            name = filterContext.Controller.GetType().Name;

        filterContext.Controller.ViewData["ControllerDisplayName"] = Name;
        base.OnActionExecuting(filterContext);
    }
}

Then you can use it in your controller as below

[ControllerDisplayName(Name ="My Account Contolller"])
public class AccountController : Controller
{
}

And in your view you can automatically use it with @ViewData["ControllerDisplayName"]

Nkosi
  • 235,767
  • 35
  • 427
  • 472
Haitham Shaddad
  • 4,336
  • 2
  • 14
  • 19
  • Thanks a lot @Haitham. Few minutes ago I got it works using OnActionExecuting of my BaseController. My fix is more complex than your way, so I'm modifying it to work as your answer. It is more elegant. – Márcio Gonzalez Sep 29 '16 at 14:32