2

I'm trying to accept a query string of the form

?param[key1]=value1&param[key2]=value2

and convert it into a Dictionary in C# MVC 4. This is trivial to do in PHP, but I haven't been able to find any method of reproducing this in C#.

I know I can take an array via

?param=value1&param=value2

but that leaves issues of ordering and isn't nearly as useful for my purposes.

In the hopes that this isn't a limitation of the framework, how might I implement a dictionary-style conversion in C#?

To clarify: I'm not looking to convert a query string into an NVC, but rather to convert query string parameters into their own NVCs. This is NOT as simple as ParseQueryString() or the Request.QueryString object.

Dan Ambrisco
  • 865
  • 7
  • 13
  • The linked "duplicate" answer doesn't properly answer this question, wish I could vote to re-open it, but this is still an issue for me in 2019 that I haven't found an elegant solution for. – akousmata May 23 '19 at 14:18

3 Answers3

2

Can't you just use the Request.QueryString collection that Asp.Net provides for you? Since you are using MVC, it will be on your controllers ControllerContext property (located on that object's HttpContext property).

marteljn
  • 6,446
  • 3
  • 30
  • 43
  • 1
    If it's MVC they should be parameters to the action method. – asawyer Jan 31 '13 at 18:48
  • @asawyer Thats a good point, but it is good to know where you can find it say if you are creating a custom model binder, you will be able to get it off the `ControllerContext`. – marteljn Jan 31 '13 at 18:52
  • The Request.QueryString NVC contains keys that would be accessed like qs["param[key1]"] whereas I'm looking to access them as qs["param"]["key1"], although ideally I'd like to simply access param["key1"] directly. – Dan Ambrisco Jan 31 '13 at 19:36
1

here I fixed some code that will work for you, defo not the best solutioin but it should work.

   string basestring = "?param[key1]=value1&param[key2]=value2";
        string newstring = basestring.Replace("?", "").Replace("param[", "").Replace("]", "");
        var array = newstring.Split('&');
        var dictionary = new Dictionary<string, string>();
        foreach (var onestring in array)
        {
            var splitedstr = onestring.Split('=');
            dictionary.Add(splitedstr[0],splitedstr[1]);
        }
Maximc
  • 1,722
  • 1
  • 23
  • 37
  • This is the solution I came to as well, but it feels rather inelegant. I was hoping there might be some automatic parsing similar to MVC's management of query strings like `?param=value1&param=value2` – Dan Ambrisco Jan 31 '13 at 19:31
0

You can also try something like this

    public ActionResult SubmitFormWithFormCollection(FormCollection parameters)
    {
        foreach (string param in parameters)
        {
            ViewData[param] = parameters[param];
        }

        return View();
    }
Nick
  • 4,192
  • 1
  • 19
  • 30