简体   繁体   中英

What the preferred way to add view-specific JavaScript to an Asp.Net Core 2 MVC application?

I have JavaScript that I'd like to add to a single Razor view ( CSHTML ), which should be associated with an input that filters a TABLE :

$(document).ready(function () {

    // added for testing
    alert('ready');

    (function ($) {

        $('#filter').keyup(function () {

            var rex = new RegExp($(this).val(), 'i');
            $('.searchable tr').hide();
            $('.searchable tr').filter(function () {
                return rex.test($(this).text());
            }).show();

        })

    }(jQuery));

});

At the moment, the code is contained in a SCRIPT tag located at the bottom of the view.

When the page loads, the alert never fires.

If I wrap the SCRIPT :

@section Head {
    <script type="text/javascript">
        $(document).ready(function () {
            // your code goes here
        });
    </script>
}

this error is produced:

InvalidOperationException: The following sections have been defined but have not been rendered by the page at '/Views/Shared/_Layout.cshtml': 'Head'. To ignore an unrendered section call IgnoreSection("sectionName").

What the preferred way to add view-specific JavaScript to an Asp.Net Core 2 MVC application?

relevant: https://stackoverflow.com/a/24895364/134367

Found the answer.

I wrapped my JAVASCRIPT in a @section Scripts block:

@section Scripts {
    <script type="text/javascript">
    $(document).ready(function () {

        alert('ready');

        (function ($) {

            $('#filter').keyup(function () {

                var rex = new RegExp($(this).val(), 'i');
                $('.searchable tr').hide();
                $('.searchable tr').filter(function () {
                    return rex.test($(this).text());
                }).show();

            })

        }(jQuery));

    });
    </script>
}

This appears to be called by @RenderSection("Scripts", required: false) in the _Layout.cshtml.

Once I did this and reloaded the page, the alert fired and the remainder of the code worked as expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM