我正在尝试在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
我该怎么办呢?
答案 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
的值将是所选选项的值。