Alex Rivera | Logout

Can I explicitly specify the NavigateUrl on a hyperlink?

Asked 2011-06-07T07:52:21.963
10

Asp.Net is awfully clever and tries to resolve the NavigateUrl of a Hyperlink relative to the control it is in or relative to the application root if you put ~/ at the start.

But I have a situation where I want to explicitly set the url to a relative path and I don't want it to 'help' me at all.

Hyperlink's navigate url and HtmlAnchor's href property both exhibit this behaviour. Is it possible to stop this behaviour - or will I have to generate the markup by hand and not use a control?

e.g. I have a user control in folder [appRoot]/foo/bar that contains asp:Hyperlinks.
I am using the control in the page [appRoot]/myPage.aspx. I want the href property of the hyperlinks, when rendered, to be exactly equal to 'donkey.gif'.

But if I write the following

 <asp:Hyperlink runat="server" NavigateUrl="donkey.gif" />

then the rendered href will be 'foo/bar/donkey.gif'.

For complicated reasons that I would rather not go into here, using "~/donkey.gif" is not an option. Also, I cannot use ResolveUrl(string url) to generate an absolute urls.

Edit
Report

1 Answer

4

Can't you simply use a HTML anchor (without the runat="server" attribute)? E.g:

<a href="relative.htm">link text</a>

Update: if you don't want to lose the functionality of the HyperLink control, you could create a control deriving from HyperLink and override the AddAttributesToRender() method (this is where the NavigateUrl is resolved).

HyperLink.AddAttributesToRender() looks like this:

protected override void AddAttributesToRender(HtmlTextWriter writer)
{
    ...
    string navigateUrl = this.NavigateUrl;
    if (navigateUrl.Length > 0 && base.IsEnabled)
    {
        string str = base.ResolveClientUrl(navigateUrl);
        writer.AddAttribute(HtmlTextWriterAttribute.Href, str);
    }
    ...
}

Custom HyperLink control:

public class MyHyperLink : HyperLink
{
  protected override void AddAttributesToRender(HtmlTextWriter writer)
  {
    if ((base.Enabled && !base.IsEnabled) && base.SupportsDisabledAttribute)
    {
      writer.AddAttribute(HtmlTextWriterAttribute.Disabled, "disabled");
    }
    base.AddAttributesToRender(writer);
    if (this.NavigateUrl.Length > 0 && base.IsEnabled)
    {
      writer.AddAttribute(HtmlTextWriterAttribute.Href, this.NavigateUrl);
    }
    if (this.Target.Length > 0)
    {
      writer.AddAttribute(HtmlTextWriterAttribute.Target, this.Target);
    }
  }
}
answered 2011-06-07T08:01:19.653

Your Answer