在自定义属性中传递自定义参数 – ASP.NET MVC

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

例如:在System.ComponentModel.DataAnnotations.Display中,我可以将值传递给参数Name

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