Convert query string dictionary (or associative array) to dictionary [duplicate]

守給你的承諾、 提交于 2019-12-14 04:19:47

问题


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.


回答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]);
        }



回答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).




回答3:


You can also try something like this

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

        return View();
    }


来源:https://stackoverflow.com/questions/14632829/convert-query-string-dictionary-or-associative-array-to-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!