I’m struggling with what would seem to be a very simple concept. If I have a value in the ViewBag intended for use by my _Layout.cshtml, how and where do I set that value?
Here are the most obvious (to me) options as I currently see them:
- Set the 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 globally (also feels wrong)
- Set the value in _ViewStart.cshtml (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 UserName value, that’s not terribly DRY. If I were tackling this with something like CodeIgniter, I’d just create my own base controller to handle these common items and go about my merry way. Is there a more preferred option with ASP.NET MVC 3?
Common view model and base controller is the way to go IMO. Use a common view model as the base class for all of your view models. Use the OnActionExecuted method in the base controller to get the view model (for an action returning a view) and cast it to the common view model. Set the common properties at that time.