ASP.NET MVC使用SelectList Query时如何在下拉列表中传递id

问题描述 投票:0回答:1

我正在尝试使用要在表单中使用的连接项填充下拉列表。我已经得到了下拉列表来显示那些连接的字符串,但我认为它没有获得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#
1个回答
1
投票

使您的查询和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.DropDownListFormodel.Employee.EmployeeID替换model.EmployeeID如下:

@Html.DropDownListFor(model => model.EmployeeID, (SelectList)ViewBag.empList, "--Select--", htmlAttributes: new { @class = "form-control"})
热门问题
推荐问题
最新问题