Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Saturday, December 9, 2017 7:51 PM
i wrote jquery code razor page but it did not work or execute but the moment i wrote it under script section then js code work........why?
@section scripts {
<script>
alert('foo');
</script>
}
All replies (5)
Saturday, December 9, 2017 8:06 PM ✅Answered
In the default layout following modern practices, the JavaScript comes after content. The scripts section makes sure the page scripts come after the script includes. Look at your layout file to see.
You can use JavaScript inline, just not reference any script libraries.
Saturday, December 9, 2017 9:48 PM ✅Answered
your sample script, does not require any libraries, or dom elements, so you can put it anywhere in a razor file as inline script.
<script>alert('hi')</script>
will work anywhere in a razor file.
Sunday, December 10, 2017 7:34 PM ✅Answered
just do a view source of page. you will see the jquery script include at the bottom (after the razor page html). so if you use the <script> tag in the razor, but not the scripts section, it will try to call the jquery object before it included. if for some reason you want to do this you have two options:
1) in the layout move the script includes to <head> section (not recommended anymore)
2) use the native onload handler
<script>
window.addEventListener("load", function(event) {
// jquery will work here becuase it after the include has run
});
</script>
Saturday, December 9, 2017 9:22 PM
this is not clear you said -- You can use JavaScript inline, just not reference any script libraries.
Saturday, December 9, 2017 11:53 PM
are you trying to say if i use jquery code in razor page then it need to be inside script tag?
if yes why?