1

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

2

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.