0

我正在从数据库中检索所有视图的标签形式和形状的统计信息,<script>其中一些将进入.<head><body>

其中一些信息由所有视图共享,例如谷歌分析,但其他信息仅特定于某些视图,例如仅在订单确认视图中可用的订单详细信息。

最终结果必须是:

<head>
    <script><!-- Google Analytics --></script>
</head>

我在布局中使用命名部分来实现我想要的:

<head>
    @RenderSection("headScripts", required: false)
</head>

<body>
    @RenderSection("bodyScripts", required: false)
</body>

示例视图代码是:

@if ((Model.Scripts.Head != null) && (Model.Scripts.Head.Count() != 0))
{

    <text>
    @section headScripts
    {
        @foreach (var script in Model.Scripts.Head)
        {
            @Html.Raw(@script.Code);
        }
    }
    </text>

}

所有视图模型都从具有 Scripts 字段的基类继承,并且我上面粘贴的代码在我的所有视图中都被复制,这是一个问题。

</body>我试图将代码移动到 PartialView,从我的布局下方的这一行开始:

@{Html.RenderAction("Index", "Scripts");}

在我的 ScriptsController 中:

public ActionResult Index()
{
    Scripts scripts = new Scripts();
    scripts.Head = whatever comes from the database;
    scripts.Body = whatever comes from the database;    

    return PartialView("/Views/Shared/scripts.cshtml", scripts);
}

一切正常,模型已正确填充并在脚本 Partial View 中可用,但遗憾@section的是无法在 PartialView 中调用,因此<script>不会显示标签。

是否有任何解决方法@if ((Model.Scripts.Head != null) && (Model.Scripts.Head.Count() != 0))以及将其余代码放在所有视图使用的一个公共位置?

4

1 回答 1

1

也许这样做

<head>
    @RenderSection("headScripts", required: false)
    @Html.RenderAction("HeadScripts", "Scripts")
</head>

<body>
    @RenderSection("bodyScripts", required: false)
    @Html.RenderAction("BodyScripts", "Scripts")
</body>

然后在您的脚本控制器中,每个调用都有两种方法

public ActionResult HeadScripts()
{
    Scripts scripts = new Scripts();
    scripts.Head = whatever comes from the database;    

    return PartialView("/Views/Shared/scripts.cshtml", scripts);
}

public ActionResult BodyScripts()
{
    Scripts scripts = new Scripts();
    scripts.Body = whatever comes from the database;    

    return PartialView("/Views/Shared/scripts.cshtml", scripts);
}

希望这可以帮助

编辑:在 PartialView 中你也不再需要@section了。

@if ((Model.Scripts.Head != null) && (Model.Scripts.Head.Count() != 0))
{
    @foreach (var script in Model.Scripts.Head)
    {
        @Html.Raw(@script.Code);
    }
}

编辑 2:使用 aBaseController和 aViewBag

public class BaseController : Controller
{
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
       ViewBag.HeadStart = whatever comes from the database;
       ViewBag.HeadEnd = whatever comes from the database;
       ViewBag.BodyStart = whatever comes from the database;
       ViewBag.BodyEnd = whatever comes from the database;
    }
}

然后在每个控制器中,您将从这个基本控制器继承

public class HomeController : BaseController
{
    // some methods here
}

最后在视图中

<head>
    @if (ViewBag.HeadStart != null)
    {
        @foreach (var script in ViewBag.HeadStart)
        {
           @Html.Raw(@script.Code);
        }
    }

    @RenderSection("headScripts", required: false)
    @* do the same for end *@
</head>
<body>
@* same thing here as well *@
</body>
于 2020-06-10T18:08:46.233 回答