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
or HtmlAnchor
, the href="#namedAnchor"
is rendered as href="controls/#namedAnchor"
(where controls
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
or HyperLink
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.
If the anchor you are linking to is on a different page as the link: In the pop-up box, click the Link to dropdown menu and select URL. Enter the full URL of the page followed by the # hashtag symbol, followed by the name of the anchor. Click Insert.
The HTML <a> element (also called the anchor element), containing its href attribute, creates a hyperlink to other web pages, locations within the same page, location to a specified title of another web page, or to an email web page. The <a> tag defines a hyperlink, which is used to link from one page to another.
The <a> tag (anchor tag) in HTML is used to create a hyperlink on the webpage. This hyperlink is used to link the webpage to other web pages or some section of the same web page. It's either used to provide an absolute reference or a relative reference as its “href” value.
Instead of using the NavigateUrl property, just use the href property
<asp:HyperLink href="#namedAnchor" runat="server">HyperLink</asp:HyperLink>
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>
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