Saturday, March 3, 2012

Using Relative path for including script and css files in UserControl


I have usercontrol that is including some js script and cs files like

<script type="text/javascript" src="/UserControl/JScripts/JScripts.js"/>
<link rel="Stylesheet" href="/UserControl/css/style.css" type="text/css" />
I am going to use this control in different pages which are in different directories.
In that case these styles/scripts not working in all pages because of relative path used in user control

For these kinds of elements, Page.ResolveClientUrl() is the perfect solution.

As this user control could be used from any web page within the web application, there will be path related issues with these <script> and <link> elements also (If paths properties are set for one page appropriately, the same path will not work other pages in different directory ).
To solve this issue, the above elements should also be modified with the ResolveClientUrl() as follows: 

<script type="text/javascript" src='<%=ResolveClientUrl("~/UserControl/JScripts/JScripts.js")%>' />
<link rel="Stylesheet" href='<%=ResolveClientUrl("~/UserControl/css/style.css")%>' type="text/css" />

Happy Coding…