Search code examples
ascx

resolving paths in aspx user control


I am building an asp.net website and wish to create a user control that includes a reference to a graphic file in a different directory. Specifically my directory structure looks like:

c:\mywebsite\ c:\mywebsite\images\ c:\mywebsite\usercontrols

The user control will be used in c:\mywebsite\default.aspx

The image is c:\mywebsite\images\logo.jpg The user control is c:\mywebsite\usercontrols\mycontrol.ascx

If in my ascx file I have:

<img src="../images/logo.jpg" />

Then this renders just fine in the Visual Studio 2010 design view, but not at run time since at run time the control is included in \default.aspx and the path relative to \default.aspx is different from the relative path from \usercontrols\mycontrol.ascx.

How should I reference the graphic from the ascx file so that it will render properly both in design preview as well as at runtime? Also I would like it to render properly in design preview for default.aspx where it is used.


Solution

  • You can use <asp:Image>... control and use the image path as relative path from the web root

    <asp:Image ImageUrl='~/Images/logo.jpg" runat="server" />