Jon Eastwood
Jon Eastwood

Reputation: 823

Handle querystring coontaining [] in asp.net

What is the best way to handle the queries[search] and sorts[Driver1] parameters in the following querystring in asp.net?

?queries[search]=greenock&id=20&sorts[Driver1]=1

I tried using this model but only id was bound:

public class ICRSRequestModel
{
    public int ID { get; set; }
    public ICollection<string> Sorts { get; set; }
    public ICollection<string> Queries { get; set; }
}

I don't have the option of changing the requesting application unfortunately, and the string contained inside [] could be any unknown value.

Upvotes: 0

Views: 53

Answers (2)

user3559349
user3559349

Reputation:

If the property is

public ICollection<string> Queries { get; set; }

Then the query string would need to be

?queries[0]=greenock

you would need to change the property to

public Dictionary<string, string> Queries { get; set; }

so that the query string could be

?queries[search]=greenock

The key will be "search" and the value will be "greenock"

Note this will only work for a single queries value. ?queries[search]=greenock?queries[anotherKey]=anotherValue will not work

Upvotes: 1

Gareth Hopkins
Gareth Hopkins

Reputation: 354

Sorry, not got 50 rep points yet else I would have commented with this probably useless comment, but here goes..

I'm sure there's a better way using MVC bindings but if all else fails it might be worth taking the QueryString from the Server.Request object and splitting the string up to extract the information you want. You can get them in to a keyvaluepair collection using the code I had lying around in a project, I'm sure it can be manipulated for your needs.

Dictionary<string, string> dictionary = new Dictionary<string, string>();
foreach (string part in queryString.Split(new char[] { '&' }))
{
   if (!string.IsNullOrEmpty(part))
   {
       string[] strArray = part.Split(new char[] { '=' });
       if (strArray.Length == 2)
       {
           dictionary[strArray[0]] = strArray[1];
       }
       else
       {
           dictionary[part] = null;
       }
   }
}

Upvotes: 0

Related Questions