javascript - 为什么这个 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 使组件选择值按预期工作。
但是不能直接使用帮助器的下拉列表工作吗?
解决方案
以下代码演示了如何创建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" })
推荐阅读
- azure - azure 密钥库权限
- javascript - 如何将 MMM('Apr') 中的月份转换为 momentjs 中的 M(4)?
- javascript - 如何在具有多列的可编辑表中创建下拉列表?
- sql - ORACLE - 如果列仅包含字符串,则为真,否则为假
- asp.net - 使用 CQRS 模式在 API 中返回有意义的错误
- python - 为什么元组中允许连接和重复?由于元组是不可变的,因此不应在任何时候更改
- android - 我的右侧工具栏中缺少约束 GUI。如何取回
- java - 无法读取 URL 中有空格的 ASPX 页面
- php - PHP - 以 3 个一组打印数组的值
- jquery - 在堆栈溢出中制作类似“标签部分”的文本