Hyperlink relative to current url, not user management path

I have a page on my site, for the purposes of this example, you can say http: //myhost/Pages/Default.aspx . In Default.aspx I have a MyControl.ascx user control that is located in /Controls/MyControl.ascx. So the tree looks something like this.

  • Root
    • Pages
      • Default.aspx
    • Control
      • Mycontrol.ascx

Whenever I put a HyperLink control in MyControl.ascx and point to NavigateUrl, this path refers to the control, not the page URL. So, for example, if I specified “AboutMe.aspx” in NavigateUrl, the URL will display as http: //myhost/Controls/AboutMe.aspx instead of http: //myhost/Pages/AboutMe.aspx . Is there any way to do this regarding the page url? I tried the solution here: Relative path from ASP.NET NavigateUrl user control , but this did not work for me.

Edit

To clarify, I would like it to be general enough so that if I didn’t know what the path would be, the solution would work. Therefore, I really do not want to specify "~ / Pages / Default.aspx" in NavigateUrl

+6
source share
5 answers

You have many options:

  • You can hardcode Url using the ~ operator, which will give you the root and then define it there: ~/Pages/AboutMe.aspx . Note that the ~ operator is only recognized for server controls and server code.

  • You can also use .. to find you where you want, as it will move around the folder structure, for example: ../Pages/AboutMe.aspx

  • You can create helper methods to return you a valid root in the Pages, Images, Javascript folder, etc.

  • HttpRequest.ApplicationPath will get your virtual application root path on the server, which you can use to create.

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 pass the relative URL to the user control through the property. Let the page that uses the control determine the relative path to the resource that will be required.

+5
source share

The best way to achieve this is to use

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

in property NavigateUrl

+2
source share

How do you install NavigateUrl hyperlinks? If I installed it using the ~ symbol, it will work as expected:

Mycontrol.ascx

 <asp:HyperLink runat="server" NavigateUrl="~/Pages/Default.aspx" ... > 
0
source share

Just in case, someone else stumbles about it, like me ...

In the code behind, I install NavigateUrl:

 link.NavigateUrl = Page.ResolveUrl("aboutus.aspx"); 
0
source share

Easier than that. Just change the usercontrol property of AppRelativeTemplateSourceDirectory to the value of the same property of the parent page.

 protected override void OnInit(EventArgs e) { AppRelativeTemplateSourceDirectory = Page.AppRelativeTemplateSourceDirectory; base.OnInit(e); } 

then all relative paths in user control will be, if they are on the page.

0
source share

All Articles