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:
Does anyone have any other suggestions/comments?
_Layout.cshtml The layout typically includes common user interface elements such as the app header, navigation or menu elements, and footer. Common HTML structures such as scripts and stylesheets are also frequently used by many pages within an app.
So, the _layout. cshtml would be a layout view of all the views included in Views and its subfolders. Setting Layout View in _ViewStart.cshtml. The _ViewStart. cshtml can also be created in the sub-folders of the View folder to set the default layout page for all the views included in that particular subfolder.
razor helps you embed serverside code like C# code into web pages. cshtml is just a file extension. razor view engine is used to convert razor pages(. cshtml) to html.
Layout pages are typically named _Layout. cshtml, the leading underscore preventing them from being browsed directly.
You can use a global action filter to add the required data to the ViewBag in all controllers:
public class LoadCmsAttribute : ActionFilterAttribute
{
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
if (!filterContext.IsChildAction &&
!filterContext.HttpContext.Request.IsAjaxRequest() &&
filterContext.Result is ViewResult)
{
var identity = new GenericIdentity("", "", true);
var principal = new GenericPrincipal(identity, new string[] { });
var cmsInterface = MvcApp.WindsorContainer.Resolve<ICMSInterface>();
cmsInterface.LoadContent(principal, 2);
var viewBag = filterContext.Controller.ViewBag;
viewBag.HeadSection = cmsInterface.GetHeadSection();
viewBag.FirstBodySection = cmsInterface.BodySection(0);
viewBag.SecondBodySection = cmsInterface.BodySection(1);
}
}
}
Global.asax:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
...
filters.Add(new LoadCmsAttribute());
}
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