【问题标题】:Enable custom scripts in _Layout.cshtml ASP.NET MVC 5在 _Layout.cshtml ASP.NET MVC 5 中启用自定义脚本
【发布时间】:2016-06-30 18:08:55
【问题描述】:

我正在构建 MVC 5,SignalR 实时通知应用程序,我想将我的工作脚本放在 _Layout.cshtml 中,因为例如在添加新项目时我想显示 toastr 通知,但脚本放置它 _Layout.cshtml 不起作用,我在 BundleConfig 中添加了脚本,但它不起作用。 注意:除了 _Layout.cshtml 之外的每个页面都可以正常工作 谁能帮我?非常感谢。 这是我的代码:

$(document).ready(function () {
toastr.options = {
    "closeButton": true,
    "debug": false,
    "newestOnTop": false,
    "progressBar": true,
    "positionClass": "toast-top-right",
    "preventDuplicates": false,
    "showDuration": "300",
    "hideDuration": "1000",
    "timeOut": "5000",
    "extendedTimeOut": "1000",
    "showEasing": "swing",
    "hideEasing": "linear",
    "showMethod": "fadeIn",
    "hideMethod": "fadeOut"
};
$(function () {

    var notificationhub = $.connection.notificationHub;

    notificationhub.client.displayMessage = function (message) {

        toastr.success(message);
        //$('#notification').html(message);
    };

    $.connection.hub.start();

}); });

如果我把它放在@section scripts{} 的任何页面上,这个脚本就可以工作 我的 _Layout 脚本部分如下所示:

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@Scripts.Render("~/bundles/notifications")
@RenderSection("scripts", required: false)

但是这种方式行不通。 如何在我的 _Layout 页面中正确实现我的脚本以显示通知。

【问题讨论】:

    标签: razor asp.net-mvc-5


    【解决方案1】:

    在您的 _Layout.cshtml 页面中,@RenderSection("scripts", required: false) 部分仅用作实现 @sections scripts {} 的页面的占位符,因此您会看到自己的行为。这是 Razor 布局引擎的一部分。

    有关所有工作原理的更多信息,请参阅 ScottGu 博客上的一篇文章,可能会有所帮助:ASP.NET MVC 3: Layouts and Sections with Razor

    为了让脚本包包含在 _Layout 基本页面中,您需要直接在页面上呈现它,就像正在呈现其他包一样。它应该看起来像这样:

    @Scripts.Render("~/bundles/scripts")
    

    **其中scripts 是您希望包含的脚本包的名称。

    现在,如果您只想直接将脚本放在页面上,您也可以这样做。只需确保使用正确的 HTML 语法正确地将其括起来即可。请记住,任何使用 _Layout.cshtml 作为其布局的页面都将包含 _Layout.cshtml 中包含的所有脚本。

    【讨论】:

      【解决方案2】:

      非常感谢 ryancdotnet,ASP.NET MVC 3: Layouts and Sections with Razor 真的很有帮助,所以我将把我的脚本放在我想使用脚本的每个页面上作为解决方案。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-11-25
        • 1970-01-01
        • 2016-10-06
        • 1970-01-01
        • 1970-01-01
        • 2014-06-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多