What is the correct way to reference Javascript in ASP.NET MVC? Using something like ../../Scripts/Myscript.js seems to work fine for routes that are the traditional {controller}/{action}/{id}, but are more fragile for anything more or less complex than that. Of greater concern is that the rational absolute reference (/Scripts/Myscript.js) breaks Intellisense in Visual Studio.
How do you handle it?
EDIT: This is obviously a very old question at this point, but I'm editing to mention that in MVC4, all you need is this:
src="~/Scripts/Whatever.js"
That's enough for Razor to figure out where you mean, using the root path.
The recommended approach is to put in a separate JavaScript file or inside a section defined in Layout page. A section can be added in the MVC Layout page using @RenderSection() directive. For example, we can define a section in Layout page under <head> tag for scripts like below.
You can create the Scripts folder in the root folder of your MVC project, and then save all JavaScript files in the Scripts folder. You can call functions defined in JavaScript files by using script blocks or event handlers.
$(function() { ValidatefuneralDate(); }); this will get invoked when the DOM is ready. $(document). on("pageload",function(){ ValidatefuneralDate(); });
In MVC we rarely uses onclick event on input element, usually we use jQuery like this: $("#elementname"). click(function () { alertMe(); }); <input value="親コード新規登録" type="button" id="elementname" />.
<script src="<%= Url.Content("~/Scripts/Myscript.js") %>" type="text/javascript"></script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With