Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hyperlink relative to current URL not path of user control

Tags:

asp.net

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: Relative path from an ASP.NET user control NavigateUrl but it didn't work for me.

Edit

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

like image 453
Kyle Avatar asked Aug 25 '10 15:08

Kyle


2 Answers

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.

like image 115
Kelsey Avatar answered Nov 08 '22 21:11

Kelsey


The best way to achieve this is to use

 string.Format("{0}", Page.Request.Url.PathAndQuery);

in NavigateUrl property

like image 2
Aftab Kalhoo Avatar answered Nov 08 '22 22:11

Aftab Kalhoo