Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to reference Javascript in ASP.NET MVC?

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.

like image 751
Jeff Putz Avatar asked Jun 02 '09 03:06

Jeff Putz


People also ask

How can add JavaScript in ASP NET MVC?

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.

Where do I put JavaScript code in MVC?

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.

How call JavaScript function on page load in MVC?

$(function() { ValidatefuneralDate(); }); this will get invoked when the DOM is ready. $(document). on("pageload",function(){ ValidatefuneralDate(); });

How can call JavaScript function on button click in ASP NET MVC?

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" />.


1 Answers

<script src="<%= Url.Content("~/Scripts/Myscript.js") %>" type="text/javascript"></script>

like image 65
CMerat Avatar answered Sep 29 '22 01:09

CMerat