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
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.