1

With C#.Net how can I add query string parameters to the URL if not present or if it present then updates the current values?

For Example –
I have URL - http://example.com/Test.aspx?foo=bar&id=100 and I wanted to update foo value to chart and also wanted to add/append new parameters as hello = world and testStatus = true to query string.


So final expected output would be – http://example.com/Test.aspx?foo=chart&hello=world&testStatus=true&id=100

John Saunders
  • 160,644
  • 26
  • 247
  • 397

4 Answers4

1
Response.Redirect("{newUrl}?param1=value&param2=value")

Edited:

Just go trough Request.QueryString.

Dictionary params = new Dictionary<string,string>();
foreach (string key in Request.QueryString)
{
    var value = Request.QueryString[key];
    //
    //Do everything you need with params
    //
    params.Add(key, value);
}
Response.Redirect("{newUrl}?" + string.Join("&", params.Select(x=>string.Format("{0}={1}", x.Key, x.Value))));
John Saunders
  • 160,644
  • 26
  • 247
  • 397
Alex Lebedev
  • 601
  • 5
  • 14
  • I wanted to check if query string key is already exists/not, if exists then I want to modify it. In the above solution if URL already contains query string Key then it re-appends. – sanvi deshpande Mar 23 '15 at 07:33
  • You can get these params by looping Request.QueryString. In the loop you can do everything you need. string urlParams = string.Empty; foreach(var param in Request.QueryString){ urlParams += string.Format("{0}={1}&", param.Key, param.Value); } Response.Redirect("{newUrl}?"+urlParams); Instead of string you can use StringBuilder. – Alex Lebedev Mar 23 '15 at 07:39
  • But I want to reform URL with existing + new + modified querystring parameters. – sanvi deshpande Mar 23 '15 at 07:41
  • please, check my updated comment. – Alex Lebedev Mar 23 '15 at 07:43
1

I wrote the following function which used in order to accomplish the required functionality :

        /// <summary>
        /// Get URL With QueryString Dynamically
        /// </summary>
        /// <param name="url">URI With/Without QueryString</param>
        /// <param name="newQueryStringArr">New QueryString To Append</param>
        /// <returns>Return Url + Existing QueryString + New/Modified QueryString</returns>
        public string BuildQueryStringUrl(string url, string[] newQueryStringArr)
        {
            string plainUrl;
            var queryString = string.Empty;

            var newQueryString = string.Join("&", newQueryStringArr);

            if (url.Contains("?"))
            {
                var index = url.IndexOf('?');
                plainUrl = url.Substring(0, index); //URL With No QueryString
                queryString = url.Substring(index + 1);
            }
            else
            {
                plainUrl = url;
            }

            var nvc = HttpUtility.ParseQueryString(queryString);
            var qscoll = HttpUtility.ParseQueryString(newQueryString);

            var queryData = string.Join("&",
                nvc.AllKeys.Where(key => !qscoll.AllKeys.Any(newKey => newKey.Contains(key))).
                    Select(key => string.Format("{0}={1}",
                        HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(nvc[key]))).ToArray());
            //Fetch Existing QueryString Except New QueryString

            var delimiter = nvc.HasKeys() && !string.IsNullOrEmpty(queryData) ? "&" : string.Empty;
            var queryStringToAppend = "?" + newQueryString + delimiter + queryData;

            return plainUrl + queryStringToAppend;
        }        

Function Usage -

Suppose given url is - http://example.com/Test.aspx?foo=bar&id=100
And you want to change foo value to chart and also you want to add new query string say hello = world and testStatus = true then -

Input to Method Call :

BuildQueryStringUrl("http://example.com/Test.aspx?foo=bar&id=100",
                new[] {"foo=chart", "hello=world", "testStatus=true"});

Output : http://example.com/Test.aspx?foo=chart&hello=world&testStatus=true&id=100

Hope this helps.

Sumit Deshpande
  • 2,155
  • 2
  • 20
  • 36
0

Try this:

if (Request.QueryString["ParamName"] == null)
  //redirect with param in then URL
else

use the answer posted here

Community
  • 1
  • 1
Stephen
  • 1,532
  • 1
  • 9
  • 17
0

Here is how you update query strings: Update Query Strings. You can simply check for value, update and then redirect.

Community
  • 1
  • 1
Ebad Masood
  • 2,389
  • 28
  • 46