Search code examples
asp.netrequest.querystring

How to retrieve multiple values for a querystring parameter in asp.net


Suppose a page is invoked with multiple values for a parameter, like:

http://example.com/mypage.aspx?x=1&x=2

I find that request.QueryString("x") = "1,2".

Okay, that's fine, I guess I can do a string.split on it to get the individual values.

But if the query is

http://example.com/mypage.aspx?x=1,2&x=3

Then request.QueryString("x") = "1,2,3".

Is there any way to distinguish multiple values from values with an embedded comma? I wistfully recall that in Java you'd get an array with a separate entry for each value.

(I tried saying "mypage.aspx?x=1%2c&x=3", but that also gives "1,2,3".)


Solution

  • I don't think there is a direct way, but you can achieve it through some workaround: mypage.aspx?x=1,2&x=3 with HttpUtility.UrlDecode(Request.QueryString.ToString()) gives output as "x=1,2&x=3"

    Code Sample:

      if (Request.QueryString != null & Request.QueryString.Count > 0)
      {
           var queryStrings = HttpUtility.UrlDecode(Request.QueryString.ToString
           ());
           var arrQueryStrings = queryStrings.Split('&');
           //var length = arrQueryStrings.Length;
           var part1 = arrQueryStrings[0];//x=1,2
           var part2 = arrQueryStrings[1];//x=3
    
          //Other option: get it from Request RawUrl and split it
          //var rawUrl = Request.RawUrl;
       }