ifooi ifooi - 13 days ago 4
Javascript Question

Can`t load JavaScript in ASP.NET

I want to test a simple JavaScript function in ASP.NET.

Movies/Index.cshtml:

<!-- My local JavaScript File -->
<script src="~/Scripts/JavaScript.js" type="text/javascript"></script>

<input type="button" id="getPeople" value="Get People"/>
<ul id="people_list"/>


Views/Shared/_Layout.cshtml:

<script src="~/Scripts/jquery-2.2.3.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="~/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="~/Scripts/JavaScript.js" type="text/javascript"></script>


/Scripts/JavaScript.js:

$(document).ready(function () {

});
$('#getPeople').click(function () {
alert("getPeople");


I press the button but no alert appears. Why?

Answer

Make sure

  • to import jQuery first (before importing /Scripts/JavaScript.js)
  • to add click handler inside document's ready event.

Check the output of your composed page (for example Developer tools in the browser), if you are uncertain.

$(document).ready(function () {
    $('#getPeople').click(function () {
        alert("getPeople");
    });
});
Comments