在局部视图使用部分 [英] Use section in partial view

查看:202
本文介绍了在局部视图使用部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的共享的布局,我想有一个脚本部分有需要的网页功能的所有脚本的东西吧。

In my shared layout I would like to have a "scripts" section to stuff it with all the scripts needed for page functionality.

Layout.cshtml

<html>
<head>
    <title>Test</title>
    <script src="@Url.Content("~/Scripts/jquery-2.0.3.js")" type="text/javascript"> </script>

    @RenderSection("Scripts", required: false)

</head>
<body>
    @RenderBody()
</body>
</html>

所以,我的看法加载特定的JavaScript和我想这是在脚本部分,它的工作。

So, my view loads a specific javascript, and I want it to be in "scripts" section, and it's working.

Index.cshtml

@model PlatformaPu.Areas.Inventura.Models.Home.Index

@section Scripts {
    <script src="@Url.Content("~/Areas/Inventura/Scripts/Home/Index.js")" type="text/javascript"></script>
}

{CONTENT REMOVED FOR BREVITY}

@section Footer {
    @Html.Partial("~/Views/Shared/_AppSelector.cshtml", Model.AppSelector)
}

最后,我的观点呈现一个片面的,我有一个JavaScript,这部分负荷。

Finally, my view renders a partial and I have a javascript that this partial loads.

_AppSelector.cshtml

@model PlatformaPu.Models.Shared._AppSelector

@section Scripts {
    <script src="@Url.Content("~/Scripts/Shared/_AppSelector.js")" type="text/javascript"></script>
}

{CONTENT REMOVED FOR BREVITY}

...这是的的工作 - JavaScript是的的在脚本部分呈现

...and this is NOT working - javascript tag is NOT rendered in "scripts" section

我怎样才能做到这一点?

How can I do this?

推荐答案

作为<一个讨论href=\"http://stackoverflow.com/questions/7556400/injecting-content-into-specific-sections-from-a-partial-view-asp-net-mvc-3-with\">this问题时,它不可能在一个局部视图中使用的部分:

As discussed in this question, it is not possible to use sections in a partial view:

部分没有局部视图的工作,这就是设计。您可以使用一些定制的助手,以实现类似的行为,但老实说它的视图的责任,包括必要的脚本,而不是部分的责任。我会用主视图的@scripts部分做到这一点,没有谐音担心脚本推荐你。

Sections don't work in partial views and that's by design. You may use some custom helpers to achieve similar behavior, but honestly it's the view's responsibility to include the necessary scripts, not the partial's responsibility. I would recommend you using the @scripts section of the main view to do that and not have the partials worry about scripts.

您应该脚本引用添加到引用部分主视图。

You should add the script reference to the main view that references the partial.

这篇关于在局部视图使用部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆