Friday, September 16, 2005

Refrencing the Root Path/URL in .NET

A common question from newbies is "How can I reference the root path of my application from controls?". It is common for many server side controls to have properties such as src (source) and hyperlinks/URL etc. ASP.NET has a neat syntax that you can use to reference the root of the applications directory in any server-side controls URL property. This syntax will relief you of having to place relative pathis in your apps directory hierachy.

Simply prefix the path with the ~ (tilda) character. During the compilation process of the server-side control, ASP.NET will translate that ~ into Request.ApplicationPath.

An example would look like img src="~/images/logo.gif" runat="server". Keep in mind that this will work for SERVER-SIDE controls only!


1 comment:

Jay Dubal said...

Hi Goyani,

There is another way of doing this (or this is the way I do) ... you cannot have img and "runat=server", this will increase the viewstate/server memory ... as server has to remember all "Runart=server" kids ;)

Make a property in pagebase / control base ... as ImagePath get { ==> return server image path here ...}

and on page do this:

img src='< %=ImagePath % >logo.gif'

Jay Dubal