且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-25 21:55:01

这很简单

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
{
}

在您的视图中,您可以自动将其与@ViewData["ControllerDisplayName"]

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