Common Data Processing Approaches in ASP.NET MVC 3 Views

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?

+7
source share
2 answers

A common presentation model and basic controller is the path to IMO. Use the generic view model as the base class for all view models. Use the OnActionExecuted method in the base controller to get the view model (for the action that returns the view) and apply it to the general view model. Set general properties at this time.

+10
source

Let's say I want ViewBag.PageHeight to have a default value of 1000 for all pages, but then it’s allowed to override any page / view. This is what I put into _Layout.cshtml:

Page height is @ (ViewBag.PageHeight? 1000)

This seems to work.

0
source

All Articles