Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create RouteValueDictionary with multivalued keys

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?

like image 296
Dave Mateer Avatar asked Feb 15 '12 14:02

Dave Mateer


1 Answers

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.

like image 59
Darin Dimitrov Avatar answered Nov 05 '22 07:11

Darin Dimitrov