Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
785 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...