Create RouteValueDictionary with multivalued keys

一曲冷凌霜 提交于 2019-12-01 15:08:56

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.

I was in the case where I don't even know the names of the keys that where provide multiple times. And since the querystring does accept multiple keys as a coma separated list. I found it helpful to write an extension method based on Darin's answer.

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