Kyle Kyle - 1 year ago 95
ASP.NET (C#) Question

Hyperlink relative to current URL not path of user control

I have a page on my site, for purposes of this example lets say http://myhost/Pages/Default.aspx. On Default.aspx I have a user control called MyControl.ascx which lives in /Controls/MyControl.ascx. So the tree looks something like this

  • Root

    • Pages

      • Default.aspx

    • Controls

      • MyControl.ascx

Whenever I place a HyperLink control on MyControl.ascx and specify a NavigateUrl, this path is relative to the control, not the URL of the page. So for instance if in NavigateUrl I specified "AboutMe.aspx", the URL would be rendered as http://myhost/Controls/AboutMe.aspx instead of http://myhost/Pages/AboutMe.aspx. Is there any way I can make this relative to the page URL? I've tried the solution here: but it didn't work for me.


To clarify, I'd like this to be generic enough so that if I didn't know what the path was the solution would work. So I don't really want to harcode "~/Pages/Default.aspx" in the NavigateUrl

Answer Source

You have a bunch of options:

  1. You could hardcode the Url using the ~ operator which give you the root and then define it from there like: ~/Pages/AboutMe.aspx. Keep in mind that the ~ operator is recognized only for server controls and in server code.

  2. You could also use the .. to get you to where you want as it will navigate back up the folder structure like: ../Pages/AboutMe.aspx

  3. You could create a helper methods to return you a valid root to your Pages folder, Images, Javascript, etc...

  4. The HttpRequest.ApplicationPath will get your the virtual application's root path on the server which you can use to build off.

For more information on Pathing options you should read this article on MSDN:

ASP.NET Web Project Paths

EDIT: Based on your edit to your question, you should then pass in the relative URL into you user control via a property. Let the page that uses the control define the relative path to the resource it will require.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download