MVC3 @Html.DropDownListFor not populating selected

2019-01-25 23:40发布

问题:

I have the following dropdown list in an MVC3 application and the selected item is not showing a value. My dropdown list is contained in a list of a custom class. My view code is as follows.

...

for (int i = 0; i < Model.PartAttributes.Count; i++)
{
    if (Model.PartAttributes[i].IsActive)
    {
        <div class="row inline-inputs">
            <label class="span5">@Model.PartAttributes[i].DisplayName:</label>
            @Html.DropDownListFor(m => m.PartAttributes[i].Value, Model.PartAttributes[i].PartList, "Choose Part")
            @Html.TextBoxFor(model => Model.PartAttributes[i].Value, new { @class = "mini" })
            @Html.ValidationMessageFor(model => Model.PartAttributes[i].Value)
            @Html.HiddenFor(model => model.PartAttributes[i].AttributeName)

        </div>
    }
}
...

The text box under the dropdown box fills correctly and the list options fill correctly. And the selected option is in the list of options to pick. What can I be doing wrong?

回答1:

Try like that:

@Html.DropDownListFor(
    m => m.PartAttributes[i].Value, 
    new SelectList(
        Model.PartAttributes[i].PartList, 
        "Value", 
        "Text", 
        Model.PartAttributes[i].Value
    ), 
    "Choose Part"
)

AFAIK the DropDownListFor helper is unable to determine the selected value from the lambda expression that is passed as first argument if this lambda expression represents complex nested properties with collections. Works with simple properties though: m => m.FooBar. I know that it kinda sucks, but hopefully this will be fixed in future versions.