I’m working on an MVC3 Razor web application which gets it’s page decoration from a java content management system. As this decoration is shared by every page I’ve put the retrieval of the CMS content in the _Layout.cshtml file but I’m not entirely happy with the code I’ve implemented…
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
@{
-- The first two lines are temporary and will be removed soon.
var identity = new GenericIdentity("", "", true);
var principal = new GenericPrincipal(identity, new string[] { });
var cmsInterface = MvcApplication.WindsorContainer.Resolve<ICMSInterface>();
cmsInterface.LoadContent(principal, 2);
}
@Html.Raw(cmsInterface.GetHeadSection())
</head>
<body>
@Html.Raw(cmsInterface.GetBodySection(0))
@RenderBody()
@Html.Raw(cmsInterface.GetBodySection(1))
</body>
</html>
As there is no controller for the _layout file I can’t see where else I could put the code to do the retrieval. Here are a few things that I’ve considered:
- Retrieve the CMS content in separate pieces so I don’t need the LoadContent call. Unfortunately, because of the component I have to use to retrieve the CMS content this isn’t possible, it is all or nothing.
- Use a partial view so I can utilise a controller. As I’d need to put the entire page into the partial that option just seems a bit ridiculous.
- Call a single static method on some helper class which retrieves the data and adds the three sections to the ViewBag. That will allow me to move the code out of the view and feels like the best solution but I’m still not particularly happy with it.
Does anyone have any other suggestions/comments?
You can use a global action filter to add the required data to the ViewBag in all controllers:
Global.asax: