I'm trying to run a jquery code which was put in my _Layout.cshtml as below:
...............
<script type='text/javascript'>
$(document).ready(function () {
alert('Test');
});
</script>
@Scripts.Render("~/bundles/jquery")
@RenderSection("Scripts", required: false)
</body>
</html>
The above code wasn't fired and when I inspected with Chrome Dev, it showed $ is not defined ( I can see all my jquery, jquery ui files are loaded )
It worked if I put this code in an external js file
I don't mind putting all my jquery code in external files, but really wanna clarify where I am doing wrong.
You need to introduce jquery before your script.
@Scripts.Render("~/bundles/jquery")
<script type='text/javascript'>
$(document).ready(function () {
alert('Test');
});
</script>
@RenderSection("Scripts", required: false)
</body>
</html>
Andreas, i have the same issue.. for default the "_layout.cshtml" has "@Scripts.Render("~/bundles/jquery")" at the end of the document, but it doesn't work.. i cut it and paste it in the head and now it is working.
In order for jQuery to work, your script should come after <script src="/Scripts/jquery-2.0.3.js"></script>
In the _Layout.cshtml, just before the </body>
tag you can find something like this
@Scripts.Render("~/bundles/jquery")
@RenderSection("scripts", required: false)
First you have the jQuery library. Then you have any scripts. That's what this means. So in your views do something like this.
@section scripts{
//your script
}
This will make sure that all scripts comes under jQuery reference.