raoul1034
raoul1034

Reputation: 187

Why don't collections get passed to via post?

I have a strongly typed view model, MyViewModel, of this structure:

public name { get; set; }
public IEnumerable<Country> { get; set; }

I populate the variables like so in a controller action, Index:

string name = GetName();
IEnumerable<Country> countries = GetCountres();

And then I create a view model and return it:

var model = new MyViewModel
{
name = name,
countries = countries
};

When Index is called, everything goes fine, I am able to use the "countries" IEnumerable in a DropDownListFor call. However, when I submit the form, POSTing to a controller that looks like so:

public ActionResult Index(MyViewModel model)

I can only access "simple" variables from my the model; string, int, decimal, bool, etc. Any IDictionariess or IEnumerables are null. I have seen examples where people simply rebind the lists from their data-access calls, but this seems silly when you have the data at the beginning. It is especially annoying when I have two multi-select boxes, where users may move items from one box to another. If they submit and validation fails, I would lose the changes they made to the boxes. Is there a way to fix this?

Upvotes: 2

Views: 86

Answers (1)

Muhammad Adeel Zahid
Muhammad Adeel Zahid

Reputation: 17794

asp.net mvc binds only those values to the model which are posted through different form fields and selectlist posts only when value (if not configured to do otherwise). so the only value that will be bound to the list is name property in your view model. the data for

IEnumerable<Country> countries

has to be filled again in post actionresult in case there is an error. As far as your second point is concerned (i believe its not happening in the code you posted) your dropdowns should post more than one value if so those values will map to IEnumerable properties of the model. you can post the code so we might help

Upvotes: 1

Related Questions