Wednesday, January 04, 2006

HyperLinks and UserControls (ASP.NET)

If you have a file (/myapp/page.aspx) which references a user control (/myapp/controls/control.ascx) that contains a HyperLink, you find that the link generated is relative to the control, not the page. For example if the following code was in the control:

<asp:HyperLink Text="Foo" NavigateUrl="bar.aspx" runat="server" />

The following output would be generated:

<a href="controls/bar.aspx">Foo</a>

This may not the desired outcome. You can set the link relative to the server root (by using /myapp/bar.aspx), site root (by using ~/bar.aspx), or even the control itself (../bar.aspx) but if you want to make it relative to the calling page more work is involved. For doing this you can use the Uri class and Request.Url:

<asp:HyperLink id="lnkFoo" Text="Foo" NavigateUrl='<%#(new Uri(Request.Url,"bar.aspx")).AbsolutePath%>' runat="server" />

If the link is in a Repeater (or something else that is bound to data) you do not need the id attribute. However if it is not, you have to add the following to the page load event of the control:

FindControl("lnkFoo").DataBind();

You then end up with a link that works:

<a id="myrepeater_lnkFoo" href="/myapp/bar.aspx">Foo</a>

Tags: ,

No comments: