2

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?

PlTaylor
  • 7,345
  • 11
  • 52
  • 94

1 Answers1

8

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.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • First of all thanks for the answer. It certainly sucks. Quick question....how did you figure that out? Where can I see that there is even an error? It just didn't work. – PlTaylor Jan 22 '12 at 12:01
  • 1
    @PlTaylor, I know it because when I first encountered this issue, I just looked at the ASP.NET MVC source code and saw how the `DropDownListFor` helper is implemented. – Darin Dimitrov Jan 22 '12 at 12:23