Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Approaches for handling common data in ASP.NET MVC 3 views

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:

  1. Set the value in each controller (not DRY)
  2. Create my own controller base inheriting from Controller and set the value in the base class
  3. Set the value in Global.asax.cs (feels dirty)
  4. Create an ActionFilter to set the data and register the filter globally (also feels wrong)
  5. 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?

like image 912
Greg Avatar asked Feb 01 '11 20:02

Greg


1 Answers

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.

like image 75
tvanfosson Avatar answered Sep 27 '22 22:09

tvanfosson