我正在研究一个MVC3 Razor Web应用程序,它从java内容管理系统中获取它的页面装饰.由于每个页面都共享这个装饰,我将CMS内容的检索放在_Layout.cshtml文件中,但我对我实现的代码并不完全满意......
<!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>
Run Code Online (Sandbox Code Playgroud)
由于_layout文件没有控制器,我无法看到我可以将代码放在哪里进行检索.以下是我考虑过的一些事情:
有没有人有任何其他建议/意见?
您可以使用全局操作筛选器将所需数据添加到所有控制器中的ViewBag:
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
Global.asax中:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
...
filters.Add(new LoadCmsAttribute());
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3287 次 |
| 最近记录: |