Using HtmlAnchor or ASP.NET HyperLink for anchor tag that navigates in-page named anchor
Solution 1
Instead of using the NavigateUrl property, just use the href property
<asp:HyperLink href="#namedAnchor" runat="server">HyperLink</asp:HyperLink>
Solution 2
To set the HREF property in codebehind:
HyperLink link = new HyperLink();
link.Attributes.Add("href", "#" + doc.DocumentID.ToString());
link.Text = doc.DocumentNumber;
This will give you:
<a href="#111">blah blah</a>
Solution 3
Set it as a custom property on the link:
HyperLink link = new HyperLink();
link.Attributes.Add("name", doc.DocumentID.ToString());
link.Text = doc.DocumentNumber;
This will give you:
<a name="111">blah blah</a>
Comments
-
Frank Schwieterman almost 2 years
I am trying to render a simple hyperlink that links to a named anchor within the page, for example:
<a href="#namedAnchor">scroll to down</a> <a name="namedAnchor">down</a>
The problem is that when I use an ASP.NET control like
asp:HyperLink
orHtmlAnchor
, thehref="#namedAnchor"
is rendered ashref="controls/#namedAnchor"
(wherecontrols
is the subdirectory where the user control containing the anchor is). Here is the code for the control, using two types of anchor controls, which both have the same problem:<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Test.ascx.cs" Inherits="TestWebApplication1.controls.Test" %> <a href="#namedAnchor" runat="server">HtmlAnchor</a> <asp:HyperLink NavigateUrl="#namedAnchor" runat="server">HyperLink</asp:HyperLink>
The generated source looks like:
<a href="controls/#namedAnchor">HtmlAnchor</a> <a href="controls/#namedAnchor">HyperLink</a>
I really just want:
<a href="#namedAnchor">HtmlAnchor</a> <a href="#namedAnchor">HyperLink</a>
I am using the
HtmlAnchor
orHyperLink
class because I want to make changes to other attributes in the code behind. I do not want to introduce a custom web control for this requirement, as the requirement I'm pursuing is not that important enough to justify abandoning the traditional ASP.NET link controls. It seems like I should be able to use the ASP.NET link controls to generate the desired link. -
misteraidan over 11 yearsThis is the correct solution for doing it in code. (Also works for HtmlAnchor class - setting the HRef property on HtmlAnchor also generates the extra "crap")
-
Rushino over 10 yearsInteresting. Thanks for this solution.
-
cdonner almost 10 yearsDoesn't validate: Attribute 'href' is not a valid attribute of element 'HyperLink'.