So I have a form that includes a list of items, and each item has a select list. My code is like so (with extraneous items removed):
@for( var i = 0; i < Model.InputSlots.Count; i++)
{
@Html.DropDownListFor(model => model.InputSlots[i].VariableId,
new SelectList(Model.Variables, "VariableId", "Name"),
"--Select Variable--",
new { @class = "span8" })
}
The drop down list displays correctly, and if I select one of the items and post the form, the selection posts correctly, but when I load the page with the VariableId set to a valid option, it does not show the selected option, but shows the default "--Select Variable--" instead.
I use the DropDownListFor in many other places in my code, and it works as expected, just not in this case. The only difference that I can tell is that it is referencing a property of an array item.
I have set a break-point in the view to verify that Model.InputSlots[i].VariableId is set to a valid option (2), and I also viewed the resulting HTML to make sure that there was an option with a value of 2 and both seemed correct, but there was no "selected" on the option element with the value of 2.
Is this a known behavior, or am I just doing something wrong somewhere that I haven't noticed?
Update:
Setting the selected item in the SelectList constructor does work, i.e.:
@Html.DropDownListFor(model => model.InputSlots[i].VariableId,
new SelectList(Model.Variables, "VariableId", "Name", Model.InputSlots[i].VariableId),
"--Select Variable--",
new { @class = "span8" })
But it does not seem to want to get it from the expression as it does in other cases.