c# - ASP.NET MVC 使用 SelectList 查询时如何在下拉列表中传递 id
问题描述
我正在尝试使用要在表单中使用的串联项目填充下拉列表。我已经获得了显示这些连接字符串的下拉列表,但我认为它无法获得 ID。(我无法提交表单,单击提交时下拉菜单闪烁),我认为这意味着没有传递任何 ID
控制器:
public ActionResult AdminCreate()
{
var query = (from e in db.Employees
select e.FullName + "-" + e.EmployeeID + "-" + e.Site.SiteName);
SelectList empList = new SelectList(query);
ViewBag.empList = empList;
return View();
}
看法:
<div class="form-group">
@Html.LabelFor(model => model.EmployeeID, "Employee", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor((model => model.Employee.EmployeeID), (SelectList)ViewBag.empList, "--Select--", htmlAttributes: new { @class = "form-control"})
@Html.ValidationMessageFor(model => model.EmployeeID, "", new { @class = "text-danger" })
</div>
</div>
解决方案
进行查询,SelecList
如下所示:
var employeeList = db.Employees.Select(e => new
{
e.EmployeeID
FullName = e.FullName + "-" + e.EmployeeID + "-" + e.Site.SiteName
}).ToList()
SelectList empList = new SelectList(employeeList,"EmployeeID","FullName");
@Html.DropDownListFor
替换为model.Employee.EmployeeID
如下model.EmployeeID
:
@Html.DropDownListFor(model => model.EmployeeID, (SelectList)ViewBag.empList, "--Select--", htmlAttributes: new { @class = "form-control"})
推荐阅读
- python - Python pygal 渲染到屏幕
- c# - 在 Chrome(Kiosk 模式)中打开 URL 并在关闭时重新打开
- ag-grid - 在 ag-grid 中以编程方式设置行分组
- keras - Keras 中的时间序列编码器-解码器 LSTM
- reactjs - 在 MobX 中,如何从 StoreA 中的 StoreB 中引用 observable
- python-3.x - Python 3.x 尝试输入 DF 列及其位置
- python - 如何在python中访问JSON文件中的数据?我想访问电子邮件数据
- python - python中字符串操作的问题
- html - 如果有标签,为什么还需要标签?
- php - 为 php ajax 播放声音通知