Passing custom parameter in custom attribute - ASP.NET MVC

你说的曾经没有我的故事 提交于 2019-11-30 09:56:26
Haitham Shaddad

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!