Razor _Layout.cshtml 中的嵌入代码

2024-04-15

我正在开发一个 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>

由于 _layout 文件没有控制器,我看不到还能在哪里放置代码来进行检索。以下是我考虑过的一些事情:

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

还有人有其他建议/意见吗?


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

全局.asax:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    ...
    filters.Add(new LoadCmsAttribute());
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Razor _Layout.cshtml 中的嵌入代码 的相关文章

随机推荐