Razor _Layout.cshtml中的嵌入式代码 [英] Embedded code in Razor _Layout.cshtml
问题描述
我正在开发一个MVC3 Razor Web应用程序,该应用程序是从Java内容管理系统获取页面装饰的.由于这种装饰是每个页面都共享的,因此我已将CMS内容的检索放置在_Layout.cshtml文件中,但是我对自己实现的代码并不完全满意...
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>
由于没有用于_layout文件的控制器,所以我看不到其他可以放置代码进行检索的位置.这是我考虑过的几件事:
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:
- 分别获取CMS内容,因此不需要LoadContent调用.不幸的是,由于我不得不使用该组件来检索CMS内容,所以这是不可能的,它是全部还是全部.
- 使用局部视图,以便可以使用控制器.因为我需要将整个页面放到部分页面中,所以这个选项似乎有点荒谬.
- 在一些帮助程序类上调用一个静态方法,该方法检索数据并将这三个部分添加到ViewBag中.这样一来,我便可以将代码移出视图,感觉是最好的解决方案,但我对此并不特别满意.
有人有其他建议/意见吗?
Does anyone have any other suggestions/comments?
推荐答案
您可以使用全局操作过滤器将所需数据添加到所有控制器中的ViewBag中:
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:
Global.asax:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
...
filters.Add(new LoadCmsAttribute());
}
这篇关于Razor _Layout.cshtml中的嵌入式代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!