问题
I'm trying to accept a query string of the form
?param[key1]=value1¶m[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¶m=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¶m[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