Senthil Natarajan Senthil Natarajan - 2 months ago 15
ASP.NET (C#) Question

Same Query String but different links

I have a scenario where each of my pages have more than 30-35 anchor elements and each one of them points to a different URL. But I want all of them to have the same query string (Google analytics UTM). Now the fun part is the URL do not change everyday they are the same but the query string changes everyday and I compute that in the code behind and that in itself is fine. What I would like to do is add the computed query string in a efficient way and without using Javascript. I know I can store the query string value in a hidden variable and then loop through the anchors in JS and add the query string, but I dont have the liberty to have JS on the page unfortunately. Any help is appreciated.

Answer

Guess you could loop through all the links and append the querystring, perhaps during the PreRender event.

var queryString = ComputeQueryStringForGoogle();
foreach (var control in this.Controls)
{
    var link = control as Hyperlink;
    if (link == null) continue;
    link.NavigateUrl += queryString;
}

or, if you prefer this style,

var queryString = ComputeQueryStringForGoogle();
foreach (var control in this.Controls)
{
    if (control is Hyperlink)
    {
        ((Hyperlink)control).NavigateUrl += queryString;
    }
}

oh heck why not a third way (I'm always learning new stuff!)

var queryString = ComputeQueryStringForGoogle();
foreach (var control in this.Controls.OfType<Hyperlink>)
{
    control.NavigateUrl += queryString;
}

or if you want to try some LINQ how about

var queryString = ComputeQueryStringForGoogle();
this.Controls.Where(t => t is Hyperlink).Select(c => { c.NavigateUrl += queryString; return c }).ToList();

Hope this wasn't overkill.