How to Properly Reference a JavaScript File in an ASP.NET Project?

DaveDev picture DaveDev · Mar 24, 2010 · Viewed 22.8k times · Source

I have some pages that reference javascript files.

The application exists locally in a Virtual Directory, i.e. http://localhost/MyVirtualDirectory/MyPage.aspx

so locally I reference the files as follows:

<script src="/MyVirtualDirectory/Scripts/MyScript.js" type="text/javascript"></script>

The production setup is different though. The application exists as its own web site in production, so I don't need to include the reference to the virtual directory. The problem with this is that I need to modify every file that contains a javascript reference so it looks like the following:

<script src="../Scripts/MyScript.js" type="text/javascript"></script>

I've tried referencing the files this way in my local setup but it doesn't work.

Am I going about this completely wrong? Can somebody tell me what I need to do?

Thanks

Answer

hunter picture hunter · Mar 24, 2010

Use ResolveUrl("~/")

<script src="<%=ResolveUrl("~/scripts/myscript.js") %>" type="text/javascript"></script>

~/ will get to you the root of your application, virtual or otherwise