Jay
Jay

Reputation: 27474

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".)

Upvotes: 1

Views: 5204

Answers (2)

codebased
codebased

Reputation: 7073

This might help you - I have just created a small console snippet for you to copy and paste to realize how it is working:

using System;
using System.Collections.Generic;
using System.Linq;

namespace Exercise1
{
    internal class Program
    {
        public static void Main()
        {
            var urlUri = new Uri(new Uri("htt://www.myapp.com/"), "news?x=1,2&x=3&x=4,5&x=");
            var queryData = urlUri.Query.Split(new[] {'&'}, StringSplitOptions.RemoveEmptyEntries);

            var resultValue = new List<string>(queryData.Count());
            resultValue.AddRange(queryData.Select(d => d.Split(new[] {'='}, StringSplitOptions.RemoveEmptyEntries)).Where(result => result != null && result.Count() == 2).Select(result => result[1]));

            foreach (var value in resultValue)
            {
                Console.WriteLine(value);
            }

            Console.ReadLine();

        }
    }

}

Basically I am first splitting by &. then I am splitting by =

Thus you can prepare an array to play with the way you want.

Here I am using Uri object, and in your case, you will read query string as is from Request.Url.Query enter image description here

Upvotes: 1

Sudipta Kumar Maiti
Sudipta Kumar Maiti

Reputation: 1709

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;
   }

Upvotes: 2

Related Questions