There are situations where you need to pass multiple values for the same parameter to the server, here are some patterns.

  • Multiple checkboxes to pick the values for the same purpose.
    • Select columns to show in the table
    • Select post categories
  • User can add as much values as he/she likes.
    • Add new tag
    • Add language
  • User can remove multiple items from a list.
    • Remove items from shopping cart

This can be handled by passing many values in one parameter with a common delimiter, or by passing multiple values as the same parameter. Here are examples with the GET method, for the POST it works the same.

Passing many values in one parameter looks like this:

http://www.bjelic.net/example?param=1,2,3,5

Passing many values as the same parameter:

http://www.bjelic.net/example?param=1&param=2&param=3&param=5

This is a common feature, the query string parameters don’t have to be unique as per RFC3986.

Even if the latter looks more verbose, there is a good reason I prefer it. When used in forms, the former would require the use of JavaScript to collect the values. The latter works out of the box.

Now there is even a better reason if you are using ASP.NET MVC, and that is that such parameters will be passed as a List.

public string Save(List languages)

And for numeric values, something like this.

public string Remove(List ids)

If in this case there is a id that can’t be cast to a integer, the route won’t be found resulting in 404 – which completely makes sense since it looks for an “Remove” action method that would accept a list of strings.

A big advantage of this is that there is no need to parse the input values, as they will be conveniently cast and assigned. Also, this enables having input models that have a list of values.

Published by Bojan Bjelić

Working hard on bunch of stuff, positive future above all. I'm blogging mostly about software, productivity and digital world.

Leave a comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.