Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace href value at runtime

Tags:

c#

asp.net

I have many A html tags in my master web page. I would like to replace their HREF values at runtime using code. How to do that? All a tags are tagged with runat="server".

like image 455
Tomas Avatar asked Mar 03 '26 21:03

Tomas


2 Answers

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);
                }
            }
        }
    }
like image 145
Mikael Östberg Avatar answered Mar 06 '26 12:03

Mikael Östberg


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";
}
like image 26
Shekhar_Pro Avatar answered Mar 06 '26 12:03

Shekhar_Pro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!