views:

180

answers:

1

How best to get an array(item=>value) pair as a GET / POST parameter?

In PHP, i can do this: URL: http://localhost/test/testparam.php?a[one]=100&a[two]=200

this gets the parameter as:

Array
(
    [a] => Array
        (
            [one] => 100
            [two] => 200
        )
)

Is there any way to accomplish the same in ASP.NET MVC?

+3  A: 

Note: Not sure about Best, but this is what I use.

You can pass the arguments using the same name for all of them:

For the URL

http://localhost/MyController/MyAction?a=hi&a=hello&a=sup

You would take the parameters as a string array (or List).

public ActionResult MyAction(string[] a)
{
     string first = a[0]; // hi
     string second = a[1]; // hello
     string third = a[2]; // sup

     return View();
}

This works for POST and GET. For POST you would name the <input> controls all the same name.

Baddie
+1: That's cool.
Robert Harvey
This seems good. But, is it possible to generate this sort of a URL with Html.RouteLink ?
sleepy
Is there a name for this type of arguments in ASP.NET MVC? (helps in googling more about this)
sleepy
@sleepy - I tried getting `Html.RouteLink` to work with this kind of URL, but when giving parameters as an anonymous object, the properties can't have the exact name. I think your best option is to build a custom HtmlHelper that outputs a proper URL.
Baddie