I want to design some controls, like Menu for instance, which have their own css and js files. I'm also going to store controls in separate directory (let's say ~/Controls). How "include" the js and css files in ~/Controls/ControlName/ directory and then refer to them properly from Web Forms, keeping in mind that aspx may be also in some di开发者_JS百科rectory tree?
I added link/script tags to the ascx file, but they seem to be working relatively, so ~/Default.aspx works, while ~/SomeFolder/Default.aspx not.
Of course I can add all references to the masterpages/pages, but I am wondering if there's another solution?
Thanks in advance
Your css and js file paths will need to be relative to the pages location.
So if the page is sitting within the Controls folder and the files are also sitting in the Controls folder the files will be referenced like so:
<script type="text/javascript" src="scripts.js"></script>
<link type="text/css" rel="Stylesheet" href="styles.css" />
However if the page was sitting in the root of the site and the files within the Controls folder you will reference the files like so:
<script type="text/javascript" src="Controls/scripts.js"></script>
<link type="text/css" rel="Stylesheet" href="Controls/styles.css" />
To resolve the css and js paths use the following code in either the master or the page:
<script type="text/javascript" src="<%= Page.ResolveUrl("~/Controls/scripts.js") %>"></script>
<link type="text/css" rel="Stylesheet" href="<%= Page.ResolveUrl("~/Controls/styles.css") %>" />
There are actually a few methods available for resolving urls depending on whether you want the url relative to the site root or the page itself.
See the following link for explanations:
Control.ResolveUrl versus Control.ResolveClientUrl versus VirtualPathUtility.ToAbsolute
精彩评论