开发者

Replace href value at runtime

I have many A html tags in my master web page. I would like to replace their HREF values at runtime using code. Ho开发者_如何学运维w to do that? All a tags are tagged with runat="server".


You have to iterate over all the controls in the ControlsCollection and update the Href property of all controls that are of type HtmlAnchor, like this:

private void UpdateTags(Control page)
    {
        foreach (Control ctrl in page.Controls)
        {
            if (ctrl is HtmlAnchor)
            {
                ((HtmlAnchor)ctrl).HRef = "myNewlink";
            }
            else
            {
                if (ctrl.Controls.Count > 0)
                {
                    UpdateTags(ctrl);
                }
            }
        }
    }


You can use HRef property of AncorTag HTML Control to change it.

like this:

<a id="anchor1" runat="server"></a>

In code

void Page_Load(object sender, EventArgs e)
{
    anchor1.HRef = "http://www.microsoft.com";
}


HtmlAnchor MyAnchor = (HtmlAnchor)e.Item.FindControl("YourAnchorID");
MyAnchor.HRef = "mypage.aspx";


You should give it an Id and then change the Href property.

<a runat="server" id="link1">link 1</a>

And then:

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


You could also make a CustomControl, extending the Hyperlink-Class and put some Logic into that. We use it to a custom hyperlink to add Trackingdata to some links.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜