首页 > 解决方案 > 为什么这个 DropDownListFor 元素不选择模型值?

问题描述

需要选择的值已确认存在于列表中,但未将其指定为已选择。

_ApproverPartial.cshtml

@Html.DropDownListFor(model => model.UserId, 
new SelectList(TempData["UserList"] as List<UserModel>, "Id", "DisplayName"), 
"Please Select", new { @class = "form-control mt-2", 
    id = "UserId-" + Model.BusinessSurveyId + "-" + Model.SectionId })

使用 JavaScript 使组件选择值按预期工作。

但是不能直接使用帮助器的下拉列表工作吗?

标签: javascriptc#asp.net-mvcrazordropdownlistfor

解决方案


以下代码演示了如何创建SelectListItem用于填充下拉列表的对象集合:

@{ 
    var model = TempData["UserList"] as List<UserModel>;

    @Html.DropDownListFor(m => model.GetEnumerator().Current,
              model.Select(d =>
              {
                  return new SelectListItem() { Text = "UserId-" + d.BusinessSurveyId + "-" + d.SectionId, Value = d.UserId };
              }),
              null, new { @class = "form-control mt-2" })
} 

使用强类型视图是合理的。
在一个动作方法中:

List<UserModel> model = /* populate the data model*/;
return View(model);

在视图中:

@model IList<UserModel>

@Html.DropDownListFor(m => Model.GetEnumerator().Current,
               Model.Select(d =>
               {
                   return new SelectListItem() { Text = "UserId-" + d.BusinessSurveyId + "-" + d.SectionId, Value = d.UserId.ToString() };
               }),
               null, new { @class = "form-control mt-2" })

推荐阅读