I struggle with what would seem like a very simple concept. If I have a value in the ViewBag intended for use by my _Layout.cshtml, how and where can I set this value?
Here are the most obvious (for me) options that I see at the moment:
- Set a value in each controller (not DRY)
- Create my own controller base inheriting from Controller and set the value in the base class
- Set the value in Global.asax.cs (feels dirty)
- Create an ActionFilter to set the data and register the filter worldwide (also not so).
- Set the value in _ViewStart.cshtml (it feels VERY wrong and VERY dirty)
For example:
_Layout.cshtml
<!DOCTYPE html> <html> <head runat="server"> <title>@ViewBag.Title</title> </head> <body> <div id="header"> <h1>Welcome @ViewBag.UserName</h2> </div> <div id="content"> @RenderBody() </div> </body> </html>
If each controller sets the value to UserName, this is not terribly DRY. If I was doing this something like CodeIgniter, I would just create my own base controller to handle these common elements and go on with my own fun. Is there a more preferred option with ASP.NET MVC 3?
Greg
source share