仅从 PartialView 声明一次脚本

usr*_*ΛΩΝ 5 jquery partial-views razor asp.net-mvc-4

我有一个可以与 Metro-UI 风格的图块配合使用的 Razor PartialView。这是一个非常简单的 PartialView,允许我显示绑定到 的图块ViewModel,实际上没什么了不起的。

由于并非所有页面都使用它,因此我不想在每个页面加载时都包含 jQuery 块。相反,我更喜欢将脚本声明为与 PartialView 内联,但在页面代码中注册一次。

视图如下(我重新设计了 Metrofy 模板)

@model IEnumerable<MetroStyleTile>


<div class="container tiles_hub">
    <div class="sixteen columns alpha">
        @foreach (MetroStyleTile tile in Model)
        {
            <div class="tile_item four columns alpha">
                <a href="@Url.Action(tile.Action, tile.Controller, routeValues: tile.MvcArea != null ? new { area = tile.MvcArea } : null)" class="tile">
                    @Html.Label(tile.Description)
                    @if (tile.ImageUrl != null)
                    {
                        @Html.Image(tile.ImageUrl.ToString(), tile.Title, htmlAttributes: new { @class = "tile_img" })
                    }
                </a>
            </div>
        }
    </div>

    @section Scripts{



        <script type="text/javascript">

            $(document).ready(function ($) {
                //Tiles hover animation
                $('.tile').each(function () {
                    var $span = $(this).children('span');
                    $span.css('bottom', "-" + $span.outerHeight() + 'px');
                });

                var bottom = 0;

                $('.tile').hover(function () {
                    var $span = $(this).children('span');
                    if (!$span.data('bottom')) $span.data('bottom', $span.css('bottom'));
                    $span.stop().animate({ 'bottom': 0 }, 250);
                }, function () {
                    var $span = $(this).children('span');
                    $span.stop().animate({ 'bottom': $span.data('bottom') }, 250);
                });
            });
        </script>
    }
</div>
Run Code Online (Sandbox Code Playgroud)

当我在页面中仅使用一次 PartialView 时,上面的代码很好,但如果我使用@Html.Partial两次,我会得到脚本两次。

现在让我澄清一下:我经常在 StackOverflow 上提问以从该平台了解更多信息,而且我通常不喜欢解决方案。

我可以使用 Javascript 全局变量来查看是否必须再次声明该函数。

我可以在布局中注册脚本,使其出现在所有页面中,而不必担心。

我问如何仅打印脚本Response一次。学习如何执行此操作可以让我在像这样开发多个 PartialView 时减轻页面负载(因此客户端仅在需要时获取脚本,并且仅在需要时获取一次脚本)。

我怎样才能做到这一点?