Access Viewbag property on all views

后端 未结 4 826
独厮守ぢ
独厮守ぢ 2021-02-14 02:22

How can I access some ViewBag properties across all my views? I want to have some information like current user name, etc accessible everywhere, but without having to to specifi

4条回答
  •  暖寄归人
    2021-02-14 03:05

    One way: Create a custom attribute, then you can apply it globally in the FilterConfig. Then you don't have to do anything in your controllers.

    public class MyCustomViewActionFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            dynamic ViewBag = filterContext.Controller.ViewBag;
    
            ViewBag.Id = "123";
            ViewBag.Name = "Bob";
        }
    }
    

    In App_Start/FilterConfig.cs:

        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new MyCustomViewActionFilter());
        }
    

    Another way if all you need is the User information. You can add the following to the top of your view:

    @using Microsoft.AspNet.Identity
    

    Then access your User Name using the following syntax:

    @User.Identity.GetUserName()
    

    You can also override the IPrincipal implementation and provide your own properties and methods to add more information you need to render.

    UPDATE: looking at MVC 6 in Asp.Net vNext this is actually baked into the framework. http://www.asp.net/vnext/overview/aspnet-vnext/vc#inj

提交回复
热议问题