views:

74

answers:

2

I'm trying to bind the selections in a multiple selection SELECT, to an IList input in the controller.

<select name="users" multiple="multiple">
  <option>John</option>
  <option>Mary</option>
</select>

class User
{
    public string Name { get; set; }
}

//Action
void Update(IList<User> users)
{
}

I've tried renaming the select as "users", "users.Name" or "users.User.Name" without success.

A: 

Hi there are two ways you can do this. The first is using the FormCollection, this returns the results as a CSV list. So the code would be something like:

[HttpPost]
public ActionResult Update(FormCollection collection)
{
    collection[0] 
    // providing this is your first item in your collection you 
    // may need to debug this to find out
}

The second option is using a parameter which will look something like:

[HttpPost]
public ActionResult Update(string[] users)
{
}

If you set values in your select box like:

<select name="users" multiple="multiple">
    <option value="1">John</option>
    <option value="2">Mary</option>
</select>

Then it will be the values in the array and not the names, in which case your action could look like:

[HttpPost]
public ActionResult Update(int[] users)
{
}
Simon G
Thank you Simon. I'm aware of these solutions, but I was willing to use complex objects instead of strings/ints or FormCollection. Thank you very much for your answer anyway
gustavogb
A: 

Try to use a ViewModel class like this:

public class TestViewModel
    {
        public List<string> Users { get; set; }
    }

And then in your Action you set that ViewModel class as an input parameter like this:

public ActionResult Save(TestViewModel model)
        {
            return View("Index");
        }

It have worked for me.

VinTem
I'm aware of this solution, I was just willing to use complex objects instead of strings/ints. Thank you very much for your answer anyway.
gustavogb