learningtech
learningtech

Reputation: 33725

.net - relative url for javascript src?

I want to include a javascript file like so

<script type="text/javascript" runat="server" src="~/file.js"></script>

The idea is that I want to include the file.js via relative path instead of an absolute path, and I want .NET to figure out the appropriate directory (ie. is it ./ or ../, or ../../ etc...).

But when I try the code above, I get compilation error.

HOw do I properly include a javascript file?

Upvotes: 4

Views: 2179

Answers (3)

Brian
Brian

Reputation: 38035

You can try this...

Razor:

<script type="text/javascript" src="@Url.Content("~/file.js")"></script>

WebForms:

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

Upvotes: 7

Kevin McKelvin
Kevin McKelvin

Reputation: 3547

If you're using MVC you can use

<script type="text/javascript" src="@Url.Content("~/file.js")" />

Upvotes: 0

n8wrl
n8wrl

Reputation: 19765

Remember that path-'relativity' is most important to the browser. Paths have to be relative to the address of the PAGE you're looking at. That's why controls and master pages that might not be in the same folders as the pages that use them go to lengths to manipulate the paths of resources they include so they work.

So in your case, drop the runat= part and if file.js is at the root of the application you should be good to go.

Upvotes: 1

Related Questions