In .NET MVC ViewData do use the drop-down box (DropDownListFor) can not select the default item data issues

Recent problems in the code thing, encountered a simple drop-down box functionality, with the following method

@Html.DropDownListFor()

Which requires a IEnumerable<SelectListItem>class passed as a parameter data, bloggers used herein ViewData, the following specific code

<div class="col-sm-8">
    @Html.DropDownListFor(t => t.Container, ViewData["Container"] as IEnumerable<SelectListItem>, new { @class = "form-control", @style = "font-size:13px" })
    @Html.ValidationMessage("Container", new { @class = "text-danger pull-right" })
</div>

Setting ViewDatadata are as follows, controllerthat the current controller, selectListItemsis a SelectListItemcollection of

List<SelectListItem> selectListItems = new List<SelectListItem>();
......
controller.ViewData["Container"] = selectListItems; 

Wherein selectListItemsthe following data, the second 'container two "dimension selected item
Here Insert Picture Description
, but in a view, and no item is selected, as shown in FIG.
Here Insert Picture Description

But then I might be ViewDatathe name of the same name with the previous expression, leading to conflict
Here Insert Picture Descriptionhave tried to modify ViewDatathe keyvalue

controller.ViewData["ContainerDDL"] = selectListItems;  
------------------
@Html.DropDownListFor(t => t.Container, ViewData["ContainerDDL"] as IEnumerable<SelectListItem>, new { @class = "form-control", @style = "font-size:13px" })

Actually solve the problem. . . . .
Here Insert Picture Description
However, it is unclear why this is so. = _ =!

Published 62 original articles · won praise 68 · views 160 000 +

Guess you like

Origin blog.csdn.net/ZUFE_ZXh/article/details/102476594