Razor _Layout.cshtml中嵌入的代码

Doc*_*ick 4 asp.net-mvc razor

我正在研究一个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文件没有控制器,我无法看到我可以将代码放在哪里进行检索.以下是我考虑过的一些事情:

  • 以单独的部分检索CMS内容,因此我不需要LoadContent调用.不幸的是,由于我必须用来检索CMS内容的组件,这是不可能的,它是全有或全无.
  • 使用局部视图,以便我可以使用控制器.因为我需要将整个页面放入部分选项中,这看起来有点荒谬.
  • 在某个帮助程序类上调用单个静态方法,该类检索数据并将这三个部分添加到ViewBag.这将允许我将代码移出视图并感觉是最好的解决方案,但我仍然不是特别满意.

有没有人有任何其他建议/意见?

Bal*_*nyi 5

您可以使用全局操作筛选器将所需数据添加到所有控制器中的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)