首页 > 解决方案 > 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> 

标签: c#

解决方案


进行查询,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"})

推荐阅读