Access Viewbag property on all views

后端 未结 4 816
独厮守ぢ
独厮守ぢ 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 02:52

    My current solution:

    Create a base controller with all needed properties (very useful and advisable).

    public abstract class BaseController : Controller {
        public string MyProperty { get; set; }
    }
    

    Inherits all your controllers, from the base controller.

    public class MyController : BaseController {
        //you can read your property here
    }
    

    In your views, add this line just after the "@model" sentence:

    @{ BaseController ctr = ViewContext.Controller as BaseController; }
    

    Now, you can use the property in your view, without populate the ViewBag, without the need of check and cast the ViewBag values, etc.

    In the view, you can use an simple inline expression:

    @(ctr.MyProperty)
    

    Or do some magic logic...

    @{
        if(ctr.MyProperty == "whatelse") {
            //do ...
        }
    }
    

    Easy, fast and comfortable.

提交回复
热议问题