asp.net user control, getting htmlAnchor resolve to href="#" asp.net user control, getting htmlAnchor resolve to href="#" asp.net asp.net

asp.net user control, getting htmlAnchor resolve to href="#"


I had the same problem, here's how I could resolve it:

Original code

User control:

<a id="foo" runat="server">...</a>

Code behind:

foo.Attributes.Add("href", "#");

Output:

<a id="..." href="../Shared/Controls/#">...</a>

Updated code

User control:

<asp:HyperLink id="foo" runat="server">...</asp:HyperLink>

Code behind:

foo.Attributes.Add("href", "#");

Output:

<a id="..." href="#">...</a>


I had a similar issue when rendering the page with PageParser.GetCompiledPageInstance() or when the url was rewritten. For some reason the HtmlAnchor always resolved incorrectly (similar to what you have above).

Ended up just using a HtmlGenericControl, since you are manipulating it server-side anyway this may be a possibility for you.

HtmlGenericControl anchor = new HtmlGenericControl("a");anchor.Attributes.Add("href", "#");


Originally I had this as a comment but by request I'm adding it as an answer since nobody else has explained why the original behavior is occurring or how to directly prevent it.

The URL rewriting is caused by the method ResolveURL on the Control class. I looked at it in Reflector and found that it will attempt to rewrite anything that it thinks is a relative URL if AppRelativeTemplateSourceDirectory is non-empty.

The simple workaround is to set this variable on the Page object to an empty string at some global level (or at least before Render), although this could be an issue if some other bit of your control structure requires it to be empty.

I suppose a true fix would be to get Microsoft to make UrlPath.IsRelativeUrl() smarter.