DropDownListFor不分配给所选值

时间:2018-06-25 18:55:15

标签: c# asp.net asp.net-mvc

我遇到了一个问题,其中我的DropDownListFor没有默认为在新列表中创建的所选值。我究竟做错了什么?我已经查看了提供的许多解决方案,但似乎都不适合我正在做的事情。

这是我的控制器代码:

List<SelectListItem> queryPlanGroupList = new List<SelectListItem>();
queryPlanGroupList = (from t in db.PlanGroups
                      orderby t.Name ascending
                      select new SelectListItem()
                      {
                          Text = t.Name,
                          Value = t.ID.ToString(),
                          Selected = (t.ID == plans.PlanGroup.ID)
                      }).ToList();
ViewBag.PlanGroupList = queryPlanGroupList;

这是我的查看代码:

<div class="form-group">
     @Html.LabelFor(model => model.PlanGroup, htmlAttributes: new { @class = "control-label" })
     @Html.DropDownListFor(model => model.PlanGroup, (List<SelectListItem>)ViewBag.PlanGroupList , "- Select one -", new { @class = "form-control" })
     @Html.ValidationMessageFor(model => model.PlanGroup, "", new { @class = "text-danger" })
</div>

2 个答案:

答案 0 :(得分:1)

Html.DropDownListFor方法使用第一个参数(用于指定视图模型属性的表达式)值来设置所选选项。 helper方法还将丢弃您在Selected上设置的任何SelectListItem属性为默认值(false)。

因此,您应将GET操作方法中的PlanGroup属性值设置为要在呈现SELECT元素时预先选择的值。

var queryPlanGroupList = (from t in db.PlanGroups
                      orderby t.Name ascending
                      select new SelectListItem()
                      {
                          Text = t.Name,
                          Value = t.ID.ToString()
                      }).ToList();
ViewBag.PlanGroupList = queryPlanGroupList;

yourViewModel.PlanGroup = plans.PlanGroup.ID;
return View(yourViewModel);

假定视图模型的PlanGroup属性与ID类的PlanGroup属性具有相同的类型。

另一种选择是使用Html.DropDownList帮助器,该帮助器尊重Selected上的SelectListItem属性

以下内容也应与您当前的操作方法代码一起使用。

@Html.DropDownList("PlanGroupList", null, "Select one", new { @class = "form-control" })

我个人更喜欢使用Html.DropDownListFor而不是Html.DropDownList,因为它是IMHO的强类型。我也更喜欢视图模型属性,而不是使用ViewBag传递选项列表:)

答案 1 :(得分:0)

我相信这是因为您需要使用模型设置默认值。在ViewModel中,将PlanGroup设置为默认要选择的值。

SelectList的Selected字段仅用于DropDownList,而不用于DropDownListFor。

编辑:事实就是如此。看到类似的问题here