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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With