0

I have list of string and i have a selected item among those strings.
Controller:

ViewBag.GroupName = new SelectList(Names, Names.Find(s=>s==Place.GroupName));

View:

 @Html.DropDownListFor(model => model.GroupName, (IEnumerable<SelectListItem>)ViewBag.GroupName)

But the selection on the view is always the first item in the list which is not as expected. What could be the problem.

4

3 回答 3

2

您需要确保传递给的第一个参数Html.DropDownListFor设置为SelectListItem当前应选择的值。如果它的值与 DropDownList 中的任何值都不匹配,则不会将任何项目设置为选中。

在您的情况下,您需要确保将model.GroupName其设置为当前应选择的 SelectListItem 的值。

例子:

。CS:

class myViewModel
{
    public string SelectedValue = "3";
    public List<SelectListItem> ListItems = new List<SelectListItem>
        {
            new SelectListItem { Text = "List Item 1", Value = "1"},
            new SelectListItem { Text = "List Item 2", Value = "2"},
            new SelectListItem { Text = "List Item 3", Value = "3"}
        };
}

.cshtml:

@model myViewModel

@Html.DropDownListFor(m => m.SelectedValue, Model.ListItems)
于 2013-07-17T16:46:58.317 回答
0

您还应该向 SelectList 提供有关 Text/Value 的信息。我想 Names 是一个字符串列表,所以你应该这样做:

从以下位置创建一个 SelectListItem 列表Names

ViewBag.GroupName = (from s in Names
                     select new SelectListItem
                     {
                         Selected = s == Place.GroupName, 
                         Text = s,
                         Value = s
                     }).ToList();

然后在视图中使用它:

@Html.DropDownList("GroupName") /*Will get from the ViewBag the list named GroupName*/
于 2013-07-17T16:36:39.650 回答
0

尝试像这样投射您的列表:

@Html.DropDownListFor(model => model.GroupName, (IEnumerable<SelectList>)ViewBag.GroupName)
于 2013-07-17T16:29:30.007 回答