Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
794 views
in Technique[技术] by (71.8m points)

asp.net mvc 3 - MVC3 @Html.DropDownListFor not populating selected item

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...