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

前端 未结 30 2553
借酒劲吻你
借酒劲吻你 2020-11-22 01:55

A common task when calling web resources from a code is building a query string to including all the necessary parameters. While by all means no rocket science, there are so

30条回答
  •  梦谈多话
    2020-11-22 02:34

    I wrote a helper for my razor project using some of the hints from other answers.

    The ParseQueryString business is necessary because we are not allowed to tamper with the QueryString object of the current request.

    @helper GetQueryStringWithValue(string key, string value) {
        var queryString = System.Web.HttpUtility.ParseQueryString(HttpContext.Current.Request.QueryString.ToString());
        queryString[key] = value;
        @Html.Raw(queryString.ToString())
    }
    

    I use it like this:

    location.search = '?@Helpers.GetQueryStringWithValue("var-name", "var-value")';
    

    If you want it to take more than one value, just change the parameters to a Dictionary and add the pairs to the query string.

提交回复
热议问题