C# SelectListItem的选定项目
我正在尝试在我的Html.DropDownListFor中设置“所选项目” 我的控制器如下所示:C# SelectListItem的选定项目,c#,asp.net-mvc,C#,Asp.net Mvc,我正在尝试在我的Html.DropDownListFor中设置“所选项目” 我的控制器如下所示: HttpCookie cookie = Request.Cookies["MyCookie"]; if (cookie != null) { model.cookieValues = new cookieValues(); model.cookieValues.formSelected = cookie.Values.Get("FormSelected"); } model.for
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);
但我无法确定如何将选定值设置为model.cookieValues.formSelected
我该怎么做呢?当您映射到
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" })
请注意,在您的下拉列表for
中有x=>x.formGroups
这是错误的,因为它是一个组列表。您需要有一个属性来绑定所选的Id(值)
例如,有一个名为
GroupId
的属性,您可以将其设置为string
(因为SelectListItem
propertyValue
是string)并在服务器上根据需要对其进行转换。您的属性formGroups
是复杂对象的集合(List
)-您无法将下拉列表绑定到集合(a
绑定并回发单个值)。例如,您的模型需要绑定到属性
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
的值与FormGroup
的ID
值中的一个匹配,那么当页面第一次呈现时,该选项将在视图中被选中。当您发回时,SelectedID
的值将是所选选项的值。非常感谢-完全按照您的代码进行操作。当我bug我可以在正确的值上看到“Selected=true”,但是当它呈现html时,没有任何东西被标记为“Selected”…奇怪。@TrevorDaniel您尝试过Ctrl+F5吗?也许您的浏览器没有使用新的更改?有时候mectrl+F5也没有什么不同。将浏览器更改为Chrome和Firefox也没有什么不同…我不理解,因为正确的列表项的值肯定是正确的true@TrevorDaniel您正在将所选项目的Id绑定到wrong属性来自模型,请查看更新。
@Html.DropDownListFor(x => x.SelectedID, Model.formGroups.Select(d => new SelectListItem ....)