从 C# 代码更改内容占位符中的 href 链接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1224966/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 13:52:43  来源:igfitidea点击:

Change href link in content place holder from C# code

c#asp.net

提问by dsteele

I have a content placeholder containing a link:

我有一个包含链接的内容占位符:

<asp:Content ID="Content5" runat="server"  contentplaceholderid="ContentPlaceHolder3">
<a href= "../WOPages/WO_Main.aspx?WONum=12345">WorkOrder</a>

and I would like to change the href querystring from code. How do I find it to change it?

我想从代码中更改 href 查询字符串。我如何找到它来改变它?

采纳答案by LukeH

If you add an idand a runat="server"attribute to your link...

如果您在链接中添加idrunat="server"属性...

<a id="YourLink" runat="server" href="../WOPages/WO_Main.aspx?WONum=12345">
    WorkOrder
</a>

...then you can access/change the HRefproperty programmatically...

...然后您可以以HRef编程方式访问/更改属性...

YourLink.HRef = "http://stackoverflow.com/";

回答by Ben Griswold

You could clear all controls from the ContentPlaceholder and then add a new hyperlink control like this:

您可以清除 ContentPlaceholder 中的所有控件,然后添加一个新的超链接控件,如下所示:

// Create your hyperlink control
HyperLink lnk = new HyperLink();
lnk.NavigateUrl = "http://domain.com";
lnk.Text = "Click here";

ContentPlaceHolder3.Controls.Clear();
ContentPlaceHolder3.Controls.Add(lnk);

or give the hyperlink an Id and update the hyperlink by finding the control in the ContentPlaceholder:

或者给超链接一个 Id 并通过在 ContentPlaceholder 中找到控件来更新超链接:

HyperLink lnk = ContentPlaceHolder3.FindControl("MyLink") as HyperLink;
lnk.NavigateUrl = "http://domain.com/update/";
lnk.Text = "Click here too";

回答by Steve

You could use render tags or do this:

您可以使用渲染标签或执行以下操作:

<a href="<asp:literal id="hrefString" runat="server"></asp:literal>"

and assign the literal in code.

并在代码中分配文字。

回答by Guffa

As the link is not a server control, the place holder contains a LiteralControl where the text is the HTML code. You can get the HTML code and replace the href attribute:

由于链接不是服务器控件,因此占位符包含一个 LiteralControl,其中文本是 HTML 代码。您可以获取 HTML 代码并替换 href 属性:

LiteralControl c = Content5.Controls[0] as LiteralControl;
c.Text = Regex.Replace(c.Text, "(href=\")[^\"]+(\")", "http://www.guffa.com");

If you add runat="server"and an id to the link so that it's a server control, it gets a lot simpler, as you can just set it's HRefproperty.

如果您runat="server"在链接中添加一个 id 以使其成为服务器控件,则它会变得简单得多,因为您只需设置它的HRef属性即可。