Create RouteValueDictionary with multivalued keys

2019-02-21 08:47发布

问题:

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

The newid parameter has several values.

My call looks like: return 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?

回答1:

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.



回答2:

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