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

时间:2016-09-29 12:31:28

标签: c# asp.net-mvc custom-attributes

我的目标是创建一个自定义属性,如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项。

有人可以帮我这个吗?

感谢。

1 个答案:

答案 0 :(得分:7)

这很简单

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

一起使用