I have a ViewModel with an enumerable property that will be set with multiple dropdown controls on a page.
My ViewModel has a collection AvailableItems
for the possible options, SelectedItems
for the return values, and PreSelectedItems
for the default values.
public class ViewModel
{
public ViewModel()
{
AvailableItems = new[]
{
new KeyValuePair<string, string>("", "unselected"),
new KeyValuePair<string, string>("key1", "value1"),
new KeyValuePair<string, string>("key2", "value2"),
new KeyValuePair<string, string>("key3", "value3"),
new KeyValuePair<string, string>("key4", "value4"),
};
}
public IEnumerable<KeyValuePair<string, string>> AvailableItems { get; set; }
public string[] SelectedItems { get; set; }
public string[] PreSelectedItems { get; set; }
}
The Controller has two actions, one is a GET
and the other a POST
. They set two different sets of PreSelectedItems
.
public ActionResult Index()
{
var viewModel = new ViewModel
{
PreSelectedItems = new[] { null, "key4", null }
};
return View(viewModel);
}
[HttpPost]
public ActionResult Index(ViewModel viewModel)
{
var oldViewModel = new ViewModel
{
PreSelectedItems = new[] { "key3", null, null },
SelectedItems = new[] { null, null, "key1" }
};
return View(oldViewModel);
}
Finally, the View displays the dropdownlists (the number of which will vary based on other parameters).
for (var i = 0; i < 3; i++)
{
<p>
@Html.DropDownListFor(model => model.SelectedItems,
new SelectList(
Model.AvailableItems,
"Key",
"Value",
Model.PreSelectedItems[i]))
</p>
}
The GET
action works absolutely fine, with the middle dropdown showing 'value4'.
The POST
action's viewModel parameter is populated correctly, but the resulting View displays the dropdowns with no preset/default values. It doesn't matter if the original ViewModel or a newly created one are returned (as long as PreSelectedItems
is populated), no default values are set.
I have no idea why it works on a GET
but not a POST
for an identical ViewModel.