How to update querystring in C#?

后端 未结 11 1147
野的像风
野的像风 2020-12-02 12:06

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 creat

相关标签:
11条回答
  • 2020-12-02 12:58

    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

    0 讨论(0)
  • 2020-12-02 12:59

    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

    0 讨论(0)
  • 2020-12-02 13:01

    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

    0 讨论(0)
  • 2020-12-02 13:05

    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}
            });
        }
    
    0 讨论(0)
  • 2020-12-02 13:06

    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"));
    
    0 讨论(0)
提交回复
热议问题