使用 HtmlAnchor 或 ASP.NET HyperLink 作为锚标记,用于导航页面内名为锚的内容
我正在尝试呈现一个链接到页面内命名锚点的简单超链接,例如:
<a href="#namedAnchor">scroll to down</a>
<a name="namedAnchor">down</a>
问题是,当我使用 asp:HyperLink
或 HtmlAnchor< 等 ASP.NET 控件时/code> 时,
href="#namedAnchor"
呈现为 href="controls/#namedAnchor"
(其中 controls
是其中的子目录)包含锚点的用户控件是)。下面是该控件的代码,使用两种类型的锚点控件,它们都有相同的问题:
<%@ 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>
生成的源代码如下所示:
<a href="controls/#namedAnchor">HtmlAnchor</a>
<a href="controls/#namedAnchor">HyperLink</a>
我真的只是想要:
<a href="#namedAnchor">HtmlAnchor</a>
<a href="#namedAnchor">HyperLink</a>
我正在使用 HtmlAnchor
或 HyperLink
类,因为我想更改后面代码中的其他属性。我不想为此需求引入自定义 Web 控件,因为我所追求的需求还没有重要到足以证明放弃传统 ASP.NET 链接控件的合理性。看来我应该能够使用 ASP.NET 链接控件来生成所需的链接。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不使用 NavigateUrl 属性,只需使用 href 属性
Instead of using the NavigateUrl property, just use the href property
要在代码隐藏中设置 HREF 属性:
这将为您提供:
To set the HREF property in codebehind:
This will give you:
将其设置为链接上的自定义属性:
这将为您提供:
Set it as a custom property on the link:
This will give you:
如果必须使用 NavigateUrl 属性(有时这是必要的),那么您可以使用:
If you must use NavigateUrl Property, which is sometimes necessary, then you can use: