SelectListItem的选定项

时间:2015-03-12 11:37:06

标签: c# asp.net-mvc

我正在尝试在Html.DropDownListFor

中设置“Selected Item”

我的控制器看起来像这样:

HttpCookie cookie = Request.Cookies["MyCookie"];
if (cookie != null)
{
    model.cookieValues = new cookieValues();
    model.cookieValues.formSelected = cookie.Values.Get("FormSelected");
}

model.formGroups = new List<SIMSClient.FormGroup>();
model.formGroups = SIMSClient.ClientFunctions.GetFormGroups(GlobalVariables.networkstuff, GlobalVariables.testAuth);

在我看来,我有一个有效的DropDownListFor:

@Html.DropDownListFor(x => x.formGroups, Model.formGroups.Select(d => new SelectListItem { Text = d.Description, Value = d.ID}), new { @id = "ddlFormGroups", @class = "form-control" })

但我无法弄清楚如何将所选值设置为model.cookieValues.formSelected

我该怎么办呢?

2 个答案:

答案 0 :(得分:1)

当您将映射设为SelectListItem时,您必须将属性Selected设置为true

假设您的model.cookieValues.formSelected保留了该组的ID,您可以测试数组中的任何项是否符合条件model.cookieValues.formSelected == group.ID

 @{ 
      groups = Model.formGroups.Select(d => 
               new SelectListItem 
               {
                  Text = d.Description, 
                  Value = d.ID,
                  Selected = (model.cookieValues.formSelected == d.ID)
               }); 
 }

@Html.DropDownListFor(x => x.GroupId , groups, new { @id = "ddlFormGroups", @class = "form-control" })

请注意,在DropDownListFor x => x.formGroups您有GroupId这是错误的,因为它是群组。您需要拥有要绑定的选定ID (值)的属性。

具有名为string的属性的示例,您可以使其SelectListItem(因为Value属性{{1}}是字符串)并根据需要将其转换为服务器。

答案 1 :(得分:1)

您的属性formGroups是复杂对象的集合(List<SIMSClient.FormGroup>) - 您无法将下拉列表绑定到集合(<select>绑定并回发单个值)。您的模型需要绑定的属性,例如

public int SelectedID { get; set; } // assumes the ID property of FormGroup is int

然后在视图中

@Html.DropDownListFor(x => x.SelectedID, Model.formGroups.Select(d => new SelectListItem ....)

如果SelectedID的值与ID的{​​{1}}值之一匹配,则在首次呈现页面时,将在视图中选择该选项。当您回发时,FormGroup的值将是所选选项的值。