2016-02-04

$ not defined while using MVC Layout View

Well, the post title should be also something like:"Where to place jQuery in MVC Layout View". It turns out there are many places available to load jQuery and most of them are not working properly. You might get Javascript error while running web page saying 'Error: '$' is undefined. This basically means that the jQuery is not yet loaded and initialized. Where to put it then?

Below is a solution that works for me. It might not be optimal, but who cares once it works, right?
I have created new section called 'MyScripts' in _Layout file:
@Scripts.Render("~/bundles/jquery")
@RenderSection("scripts", required: false)
@RenderSection("MyScripts", required: false)
So in the view file, I can use something like:
@section MyScripts {
    <script type="text/javascript">
        $("#eta_table");
        ...
    </script>
}

No comments:

Post a Comment