Replace href value at runtime

I have many html tags on my main web page. I would like to replace their HREF values ​​at runtime with code. How to do it? All tags are marked with runat = "server".

+3
source share
5 answers

You need to iterate over all the controls in ControlsCollectionand update the property of Hrefall the controls of the type HtmlAnchor, for example:

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);
                }
            }
        }
    }
+2
source

You can use the HRef AncorTag HTML Control property to modify it.

like this:

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

In code

void Page_Load(object sender, EventArgs e)
{
    anchor1.HRef = "http://www.microsoft.com";
}
+2
source
HtmlAnchor MyAnchor = (HtmlAnchor)e.Item.FindControl("YourAnchorID");
MyAnchor.HRef = "mypage.aspx";
+2

, Href.

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

:

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

You can also make CustomControl by extending Hyperlink-Class and introducing some logic into it. We use it for a custom hyperlink to add Trackingdata to some links.

0
source

All Articles