48

Somewhere in the url there is a &sortBy=6 . How do I update this to &sortBy=4 or &sortBy=2 on a button click? Do I need to write custom string functions to create the correct redirect url?

If I just need to append a query string variable I would do

string completeUrl = HttpContext.Current.Request.Url.AbsoluteUri + "&" + ...
Response.Redirect(completeUrl);

But what I want to do is modify an existing querystring variable.

developer747
  • 15,419
  • 26
  • 93
  • 147

11 Answers11

125

To modify an existing QueryString value use this approach:

var nameValues = HttpUtility.ParseQueryString(Request.QueryString.ToString());
nameValues.Set("sortBy", "4");
string url = Request.Url.AbsolutePath;
Response.Redirect(url + "?" + nameValues); // ToString() is called implicitly

I go into more detail in another response.

Community
  • 1
  • 1
Ahmad Mageed
  • 94,561
  • 19
  • 163
  • 174
10

Retrieve the querystring of sortby, then perform string replace on the full Url as follow:

string sUrl = *retrieve the required complete url*
string sCurrentValue = Request.QueryString["sortby"];
sUrl = sUrl.Replace("&sortby=" + sCurrentValue, "&sortby=" + newvalue);

Let me know how it goes :)

Good luck

m.othman
  • 638
  • 7
  • 28
9
    private void UpdateQueryString(string queryString, string value)
    {
        PropertyInfo isreadonly = typeof(System.Collections.Specialized.NameValueCollection).GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
        isreadonly.SetValue(this.Request.QueryString, false, null);
        this.Request.QueryString.Set(queryString, value);
        isreadonly.SetValue(this.Request.QueryString, true, null);
    }
Mathias Nohall
  • 737
  • 1
  • 9
  • 9
  • This is the best way to go if you can't/don't want to use Response.Redirect or any postback methods – Lucas Apr 26 '16 at 14:29
2

Based on Ahmad Solution I have created following Method that can be used generally

private string ModifyQueryStringValue(string p_Name, string p_NewValue)
{

    var nameValues = HttpUtility.ParseQueryString(Request.QueryString.ToString());
    nameValues.Set(p_Name, p_NewValue);
    string url = Request.Url.AbsolutePath;
    string updatedQueryString = "?" + nameValues.ToString();
    return url + updatedQueryString;
}

and then us it as follows

Response.Redirect(ModifyQueryStringValue("SortBy","4"));
Sabyasachi Mishra
  • 1,677
  • 2
  • 31
  • 49
2

If you really want this you need to redirect to new same page with changed query string as already people answered. This will again load your page,loading page again just for changing querystring that is not good practice.

But Why do you need this?

If you want to change the value of sortBy from 6 to 4 to use everywhere in the application, my suggession is to store the value of query string into some variable or view state and use that view state everywhere.

For e.g.

in Page_Load you can write

if (!IsPostBack)
{
  ViewState["SortBy"] = Request.QueryString["sortBy"];
}

and everywhere else ( even after postback ) you can use ViewState["SortBy"]

Imran Rizvi
  • 7,331
  • 11
  • 57
  • 101
  • I need to preserve state between different pages. Viewstate works only for postbacks to the same page. – developer747 Mar 19 '12 at 14:20
  • then you can use Session instead of ViewState – Imran Rizvi Mar 19 '12 at 14:21
  • I am aware of the server side options. I could also use cookies. But if I can get the query string to work, that would be ideal. – developer747 Mar 19 '12 at 14:25
  • can you send more details about your exact requirement, cause taking value from querystring all time is not reliable, what if user initially enter a value in query string to load a page, and after changing something before clicking on say save/update button he changes value in querystring. Your querystring value will not match to save data to proper record. – Imran Rizvi Mar 19 '12 at 14:30
  • @ImranRizvi, it can be hashed if security is a concern –  Jul 03 '16 at 12:38
0

You need to redirect to a new URL. If you need to do some work on the server before redirecting there you need to use Response.Redirect(...) in your code. If you do not need to do work on the server just use HyperLink and render it in advance.

If you are asking about constructing the actual URL I am not aware of any built-in functions that can do the job. You can use constants for your Paths and QueryString arguments to avoid repeating them all over your code.

The UriBuilder can help you building the URL but not the query string

Stilgar
  • 22,354
  • 14
  • 64
  • 101
0

The only way you have to change the QueryString is to redirect to the same page with the new QueryString:

Response.Redirect("YourPage.aspx?&sortBy=4")

http://msdn.microsoft.com/en-us/library/a8wa7sdt(v=vs.100).aspx

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
Massimiliano Peluso
  • 26,379
  • 6
  • 61
  • 70
0

You can do it clientside with some javascript to build the query string and redirect the page using windows.open.

Otherwise you can use Response.Redirect or Server.Transfer on the server-side.

Strillo
  • 2,952
  • 13
  • 15
0

SolrNet has some very helpful Url extension methods. http://code.google.com/p/solrnet/source/browse/trunk/SampleSolrApp/Helpers/UrlHelperExtensions.cs?r=512

    /// <summary>
    /// Sets/changes an url's query string parameter.
    /// </summary>
    /// <param name="helper"></param>
    /// <param name="url">URL to process</param>
    /// <param name="key">Query string parameter key to set/change</param>
    /// <param name="value">Query string parameter value</param>
    /// <returns>Resulting URL</returns>
    public static string SetParameter(this UrlHelper helper, string url, string key, string value) {
        return helper.SetParameters(url, new Dictionary<string, object> {
            {key, value}
        });
    }
James Hull
  • 3,669
  • 2
  • 27
  • 36
0

I think you could perform a replacement of the query string in the following fashion on your server side code.

NameValueCollection filtered = new NameValueCollection(request.QueryString);

filtered.Remove("SortBy");
filtered.Add("SortBy","4");
legrandviking
  • 2,348
  • 1
  • 22
  • 29
  • I am looking for something along the lines that you recommend. But if I do filtered.Remove("SortBy"); will it also remove the value (=2" and the pefix string "&" ? Thats what I need. – developer747 Mar 19 '12 at 14:23
  • This methods provides you with a dictionnary of key / values where key is the parameter name and value is the value of the parameter. If you remove sortBy this will also remove the value and the &. I would need to try it to be 100% sure though, i have not worked on server code in a while. – legrandviking Mar 19 '12 at 17:47
0

The query string is passed TO the server. You can deal with the query string as a string all you like - but it won't do anything until the page is ready to read it again (i.e. sent back to the server). So if you're asking how to deal with the value of a query string you just simply access it Request.QueryString["key"]. If you're wanting this 'change' in query string to be considered by the server you just need to effectively reload the page with the new value. So construct the url again page.aspx?id=30 for example, and pass this into a redirect method.

SkonJeet
  • 4,827
  • 4
  • 23
  • 32