我有问题。我想通过RouteValueDictionary通过RedirectToAction传递字典。有可能这样做吗?
我有一个POST方法:
[HttpPost]
public ActionResult Search(MyViewModel _myViewModel)
{
IDictionary<string, string> parameters = new Dictionary<string, string>();
foreach (var item in _myViewModel)
{
parameters.Add(item.ValueId, item.ValueName);
}
return RedirectToAction("Search", new RouteValueDictionary(parameters));
}
我想要一个这样的网址:
http://localhost:26755/Searcher/Search?id1=value1&id2=value2&id3=value3
GET方法应该如何?
[HttpGet]
public ActionResult Search( **what's here?** )
{
(...)
return View(myViewModel);
}
答案 0 :(得分:2)
首先,我们需要修复执行重定向的Search
操作。如果要在重定向时获取所需的查询字符串参数,则应使用IDictionary<string, object>
而不是IDictionary<string, string>
:
[HttpPost]
public ActionResult Search(MyViewModel _myViewModel)
{
IDictionary<string, object> parameters = new Dictionary<string, object>();
foreach (var item in _myViewModel)
{
parameters.Add(item.ValueId, item.ValueName);
}
return RedirectToAction("Search", new RouteValueDictionary(parameters));
}
并且在目标控制器操作中完成后,您可以在请求中使用QueryString
字典:
[HttpGet]
public ActionResult Search()
{
// this.Request.QueryString is the dictionary you could use to access the
// different keys and values being passed
// For example:
string value1 = this.Request.QueryString["id1"];
...
// or you could loop through them depending on what exactly you are trying to achieve:
foreach (string key in this.Request.QueryString.Keys)
{
string value = this.Request.QueryString[key];
// do something with the value here
}
...
}