我想返回RedirectToRouteResult
,将用户发送到以下网址:
/MyController/MyAction/id?newid=3&newid=5&newid=7
newid
参数有几个值。
我的通话如下:return RedirectToAction(string.Empty, routeValues);
这是我到目前为止所尝试过的,但是不起作用:
// ...?newid%5B0%5D=3&newid%5B1%5D=5&newid%5B2%5D=7
var routeValues = new RouteValueDictionary {
{"id", myid},
{"newid[0]", 3},
{"newid[1]", 5},
{"newid[2]", 7},
};
// ...?newid=System.Int32%5B%5D
var routeValues = new { id = myid, newid = new int[] { 3, 5, 7 } };
// ...?newid=System.String%5B%5D
var routeValues = new { id = myid, newid = new string[] { "3", "5", "7" } };
// ...?newid=System.Int32%5B%5D
var routeValues = new RouteValueDictionary {
{"id", myid},
{"newid", new int[] { 3, 5, 7 } }
};
使这项工作的秘诀是什么?
答案 0 :(得分:13)
这是框架中真正缺少的一件事。你最好的选择是手动滚动它:
public ActionResult Foo()
{
var ids = new[] { 3, 5, 7 };
var url = new UriBuilder(Url.Action("MyAction", "MyController", new { id = "123" }, Request.Url.Scheme));
url.Query = string.Join("&", ids.Select(x => "newid=" + HttpUtility.UrlEncode(x.ToString())));
return Redirect(url.ToString());
}
将其置于自定义扩展方法中可以提高当然的可读性。
答案 1 :(得分:0)
我遇到的情况是我甚至不知道多次提供的键的名称。由于查询字符串确实接受多个键作为逗号分隔列表。我发现根据Darin的答案编写扩展方法很有帮助。
public static UriBuilder TransformToMultiplyKeyUrl(this RouteValueDictionary self, string baseUrl)
{
var url = new UriBuilder(baseUrl);
//Transform x=y,z into x=y&x=z
url.Query = String.Join("&",
self.SelectMany(
pair => ((string)pair.Value).Split(',')
.Select(v => String.Format("{0}={1}", pair.Key, HttpUtility.UrlEncode(v)))));
return url;
}