1

I have a question about relative path to external javascript, css and images files in Asp.C# application.

I have pages with 2 - 5 sub levels so my javascript and css files looks like

../../../../../javascriptfile.js
../../../cssfile.css
../../../../../../image.jpg

In case if it will be additional sub level application won't find files.

What is the best practices to specify path to file???

1
  • the answer will be just to reorganize the files to reduce the usage of such relative path :) Commented Mar 6, 2011 at 17:13

3 Answers 3

6

Keep in mind when considering these answers that "root-relative" and "root of the site" may really mean the root of the path following the domain name in the url. You may need to take into account scenarios where your web site is not located at the root. In such scenarios, root-relative paths would potentially point to a different web site.

In ASP.NET you can use a leading ~ to generate urls relative to the root of current site for most server-side controls, as in: <img src="~/image.jpg" runat="server">

You can also use the ResolveUrl method (and other similar methods) to expand such paths without using server-side controls.

Sign up to request clarification or add additional context in comments.

1 Comment

This has the added bonus of working wonderfully in master pages, and more consistently with advanced routing techniques. Keep in mind that the same page (or masterpage) may be referred to from different paths within your application.
1

Use a root-relative path like this:

    /js/javascriptfile.js
    /css/style.css

the first / means at the root of the site.

1 Comment

I generally avoid referencing scripts like this to avoid virtual path issues. This works if you're sure your project will always be hosted out of the root of the web server, but I know personally that is rarely if ever the case. The ResolveUrl tip above is a much safer bet.
0

Use absolute or root-relative paths to avoid confusion in multi-level pages.

Look here for more information: http://www.motive.co.nz/glossary/linking.php

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.