Razor 在_Layout.cshtml ASP.NET MVC 5中启用自定义脚本

Razor 在_Layout.cshtml ASP.NET MVC 5中启用自定义脚本,razor,asp.net-mvc-5,Razor,Asp.net Mvc 5,我正在构建MVC 5,SignalR实时通知应用程序,我想将我的工作脚本放在_Layout.cshtml中,因为例如,在添加新项目时,我想显示给STR通知,但脚本将其放在_Layout.cshtml中不工作,我在BundleConfig中添加了脚本,但它不工作。 注意:除了_Layout.cshtml之外,所有内容都可以在每个页面上正常工作 有人能帮我吗?非常感谢。 这是我的密码: $(document).ready(function () { toastr.options = { "c

我正在构建MVC 5,SignalR实时通知应用程序,我想将我的工作脚本放在_Layout.cshtml中,因为例如,在添加新项目时,我想显示给STR通知,但脚本将其放在_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{}
“我的布局脚本”部分如下所示:

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@Scripts.Render("~/bundles/notifications")
@RenderSection("scripts", required: false)
@Scripts.Render("~/bundles/scripts")
但这种方式行不通。
如何在我的_Layout页面中正确地实现我的脚本以显示所有通知。

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

有关这一切如何运作的更多信息,请参阅ScottGu博客上的一篇文章:

为了让脚本包包含在_布局基本页面上,您需要直接在页面上呈现它,就像呈现其他包一样。它应该是这样的:

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@Scripts.Render("~/bundles/notifications")
@RenderSection("scripts", required: false)
@Scripts.Render("~/bundles/scripts")
**其中
scripts
是您希望包含的脚本包的名称


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

多亏了ryancdotnet, 是真正有用的,所以我将把我的脚本放在我想使用脚本的每个页面上作为解决方案