C# 在自定义属性中传递自定义参数-ASP.NET MVC

C# 在自定义属性中传递自定义参数-ASP.NET MVC,c#,asp.net-mvc,custom-attributes,C#,Asp.net Mvc,Custom Attributes,我的目标是创建一个自定义属性,如System.ComponentModel.DataAnnotations.Display,它允许我传递参数 例如:在System.ComponentModel.DataAnnotations.Display中,我可以向参数名传递一个值 [Display(Name = "PropertyName")] public int Property { get; set; } 我想做同样的事情,但在控制器和行动如下 [CustomDisplay(Na

我的目标是创建一个自定义属性,如System.ComponentModel.DataAnnotations.Display,它允许我传递参数

例如:在System.ComponentModel.DataAnnotations.Display中,我可以向参数名传递一个值

[Display(Name = "PropertyName")]
public int Property { get; set; }
我想做同样的事情,但在控制器和行动如下

[CustomDisplay(Name = "Controller name")]
public class HomeController : Controller
然后用其值填充ViewBag或ViewData项

我该怎么做?

这很简单

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);
    }
}
然后您可以在控制器中使用它,如下所示

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

在您的视图中,您可以将其与
@ViewData[“ControllerDisplayName”]

一起自动使用。您必须使用
ViewContext来反思控制器类型。Controller
refere CustomAttributes不允许在ViewBag或viewdatarefere中存储数据,然后将结果分配给
ViewBag
非常感谢@Haitham。几分钟前,我使用BaseController的OnActionExecuting使它工作。我的修正比你的方法更复杂,所以我修改它作为你的答案。它更优雅。