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.
A more simple solution would be to set the href attribute of the asp:hyperlink instead of using NavigateUrl property:
hyperlink1.Attributes("href") = "exactpath.gif"
hyperlink1.Attributes("href") = ResolveUrl("~/dir/page.aspx")
As of .NET4 you can also just set the href attribute directly like this:
<asp:Hyperlink runat="server" href="donkey.gif" />
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);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With