Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable custom scripts in _Layout.cshtml ASP.NET MVC 5

I'm building MVC 5, SignalR Real time notification app, I want place my working scripts in _Layout.cshtml, because for example on add new item I want display toastr notification, but scripts placed it _Layout.cshtml not working, I've added scripts in BundleConfig, but it's not working. Note: everything works fine on every page except _Layout.cshtml can anyone help me? Lot of thanks. Here is my code:

$(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();

}); });

This script works if I'm place it on any page in @section scripts{} My _Layout scripts section looks like this:

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

But this way not works. how can I implement my script correctly in my _Layout page to display notifications everywere.

like image 529
Archil Labadze Avatar asked Mar 04 '26 20:03

Archil Labadze


1 Answers

In your _Layout.cshtml page, the portion @RenderSection("scripts", required: false) is only serving as a placeholder for pages that implement the @sections scripts {}, hence why you are seeing the behavior you are. This is part of the layout engine for Razor.

For more information on how that all works, here is an article on ScottGu's blog that may help: ASP.NET MVC 3: Layouts and Sections with Razor

In order to get the script bundle to be included on the _Layout base page, you need to directly render it on the page, just like the other bundles are being rendered. It should look something like this:

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

**Where scripts is the name of the script bundle you wish to include.

Now if you want to just directly put the script on the page, you can do that as well. Just make sure you enclose it properly with the correct HTML syntax. And remember that any page that uses the _Layout.cshtml as it's layout will have all the scripts included on _Layout.cshtml.

like image 154
ryancdotnet Avatar answered Mar 08 '26 20:03

ryancdotnet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!