Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

How do you get a server control HTMLAnchor to have href="#". It keeps resolving the "#" to the control path.

<a href="#" runat="server" />
resolves to: <a href="../ControlPath/#">

I can't seem to get a google search to give me the results i want so i figured i'd ask here.

EDIT: Syntax.

Removing the runat server is not an option. It's manipulated in the backend, this was just a simplification.

like image 681
Highstead Avatar asked Sep 28 '09 20:09

Highstead


3 Answers

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>
like image 170
Ramses Avatar answered Oct 08 '22 20:10

Ramses


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", "#");
like image 38
Brendan Kowitz Avatar answered Oct 08 '22 18:10

Brendan Kowitz


Brendan Kowitz solution will work, however i was not able to implement it due to the way this control is to operate. I ended up having to hack it as per the following code in the code behind:

lnk.Attributes.Add("href",Page.Request.Url.ToString() + "#");

Where lnk is an HtmlAnchor.

The reason for this issue in the first place is the control is not in the same directory as the page, and .Net goes about "intelligently" fixing your problem for you. The above will work, though if anyone has a better solution i'm all ears.

like image 43
Highstead Avatar answered Oct 08 '22 18:10

Highstead