posted 6/27/2011 by Hajan Selmani
Sometimes developers are in need to get the Base Page URL so that they can easily create URL's in their server or client side. This is especially very much needed when you work with Master pages or master layout and have other pages that use that master pages.
This is also important if you, for example, develop your website on your local development server or in an child application of an Web Site on your IIS web server (such as child application in your Default Website). Therefore, you will access the website int he following way: http://localhost/WebsiteName/<your-resources-and-pages>. So, once you move your website to public and give it a real domain name like www.yourdomain.com, there is quite big possibiilty to have issues with links to your resources and links between pages in your website especially if you haven't taken this into consideration.
A good way I have been using sometime ago is to create BasePage helper method or BasePage field that will help you return the current base page and then append the resource or page to it. This way you won't have headache whenever you change the Base Page location either in your development environment or in your public site.
The C# code I want to share with you is the following:
/// <summary> /// Gets page Base Url /// </summary> public static string BaseUrl { get { Uri url = HttpContext.Current.Request.Url; string root = url.Scheme + "://" + url.Authority + HttpContext.Current.Request.ApplicationPath; if (!root.EndsWith("/")) root += "/"; return root; } }
Usage
Without using BaseUrl:
Lets say I have image in the following location <root>/images/myPicture.png.
Now I want to display the image in my Web User Control which is in location <root>/Controls/MyControl.ascx
If I do this:
<img src="../images/myPicture.png" />- this will work if my page (where I use MyControl.ascx) is in the same location with my control <root>/Controls/MyPage.aspx, but it won't work if my page is in different location level, like for example <root>/MyPage.aspx since the location points to one level up then images/myPicture.png, which logically does not exists. So, to avoid this type of problems, we can use our BaseUrl field to get the Base Url and just bind the other part of the path to the resource.
Using the BaseUrl:
<img src="<%= BaseUrl %>/images/myPicture.png" />
Of course, you need to import the Namespace to your BaseUrl, but you can directly type it in the following format order: <%= Namespace.Class.BaseUrl %>
The same can be done using javascript too.
Hope this was helpful.
Hajan
What kind of email newsletter would you prefer to receive from CodeAsp.Net?18