Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing custom parameter in custom attribute - ASP.NET MVC

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?

like image 269
Márcio Gonzalez Avatar asked Sep 29 '16 12:09

Márcio Gonzalez


Video Answer


1 Answers

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

like image 110
Haitham Shaddad Avatar answered Sep 25 '22 12:09

Haitham Shaddad