0

I want to add multiple query string key value pairs to an url by formatting a regular string and then appending this to the current query string. Because, in my knowledge, there is no way to change the actual Request.QueryString. Therefore I try to append the kvp:s to the query string as per below. I have searched StackOverflow, but I couldn't find an answer that matches my problem.

protected void ServiceSelectionChanged(object sender, EventArgs e)
{
    var regNr = registrationNumber.Text;
    var selectedServiceType = SelectedServiceType.ToString("D");

    string url = string.Empty;
    BookingHelpers.FormatQueryStringUrl(this.Request, "serviceType", selectedServiceType, ref url);
    BookingHelpers.FormatQueryStringUrl(this.Request, "regNr", regNr, ref url);
    Server.Transfer(url, false);
}

public static void FormatQueryStringUrl(HttpRequest request, string key, string value, ref string url)
{
    if (string.IsNullOrEmpty(url))
    {
        url = request.Url.PathAndQuery; 
    }
    if (url.Contains("?"))
    {
        if (url.Contains("&" + key))
        {
            string currentValue = request.QueryString[key];
            url = url.Replace("&" + key + "=" + currentValue, "&" + key + "=" + value);
        }
        else
        {
            url = String.Format(request.Url.PathAndQuery + "&" + key + "={0}", value);
        }
    }
    else url = String.Format(request.Url.PathAndQuery + "?" + key + "={0}", value);
}

This however uses the Request.QueryString each time, so the first kvp is overwritten. So my question is: How can I make this work so that i can append both of the key value pairs to the query string?

David
  • 101
  • 1
  • 3
  • 15

1 Answers1

0

I found an answer on stack overflow that helped me:

How to build a query string for a URL in C#?

Although, I also needed to check if the url already had a query string in it, so i modified it to something like this.

public static string ToQueryString(string url, NameValueCollection nvc)
    {
        StringBuilder sb;

        if (url.Contains("?"))
            sb = new StringBuilder("&");
        else
            sb = new StringBuilder("?");

        bool first = true;

        foreach (string key in nvc.AllKeys)
        {
            foreach (string value in nvc.GetValues(key))
            {
                if (!first)
                {
                    sb.Append("&");
                }

                sb.AppendFormat("{0}={1}", Uri.EscapeDataString(key), Uri.EscapeDataString(value));

                first = false;
            }
        }

        return url + sb.ToString();
    }

And the usage instead became:

var queryParams = new NameValueCollection() 
{
    { "isaServiceType", selectedIsaServiceType },
    { "regNr", regNr }
};

var url = ToQueryString(Request.Url.PathAndQuery, queryParams);
Community
  • 1
  • 1
David
  • 101
  • 1
  • 3
  • 15