Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net mvc4 jquery not working

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.

like image 558
davidcoder Avatar asked Aug 29 '12 08:08

davidcoder


3 Answers

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>
like image 174
NunoCarmo Avatar answered Oct 16 '22 11:10

NunoCarmo


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.

like image 23
user1462933 Avatar answered Oct 16 '22 11:10

user1462933


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.

like image 7
DanKodi Avatar answered Oct 16 '22 10:10

DanKodi