与多值键创建RouteValueDictionary [英] Create RouteValueDictionary with multivalued keys

查看:111
本文介绍了与多值键创建RouteValueDictionary的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想返回一个 RedirectToRouteResult 发送用户像下面这样的URL:

I'd like to return a RedirectToRouteResult that sends users to a URL like the following:

/MyController/MyAction/id?newid=3&newid=5&newid=7

NEWID 参数有几个值。

我的电话如下:返回RedirectToAction(的String.Empty,routeValues​​);

下面是我到目前为止已经试过,并且不工作:

Here is what I have tried so far, and that do not work:

// ...?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 } }
};

什么是做这项工作的秘诀是什么?

What is the secret to make this work?

推荐答案

这是一件事,真的从框架遗漏。最好的办法是手动滚吧:

That's one thing that's really missing from the framework. Your best bet is to manually roll it:

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());
}

把这个变成一个自定义的扩展方法可能会增加课程的可读性。

Putting this into a custom extension method could increase the readability of course.

这篇关于与多值键创建RouteValueDictionary的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆