使用DropDownList在视图中编辑多个记录

时间:2015-03-10 19:54:33

标签: c# asp.net-mvc

我能够从一个控制器编辑多个记录,但是在视图中编辑多个记录时,我无法成功添加DropDownList

控制器:

public ActionResult ReportByNumber() 
{
    ViewBag.Department = new SelectList(from r in db.Departments select r, "Name", "Name");
    return View(reportList.ToList());
}

查看允许多条记录:

@for (int i = 0; i < Model.Count; i++) { 

@Html.TextBoxFor(m => m[i].Department, new { @style = "width:120px" })

}

有没有办法让Department成为DropDownList

3 个答案:

答案 0 :(得分:0)

试试这个: 首先在你的控制器

public ActionResult ReportByNumber() 
{
ViewBag.DepartmentID = new SelectList(from r in db.Departments select r, "DepartmentID", "Name",selectedDepartment);
return View();
}

您认为的第二个

@Html.DropDownList("DepartmentID", null, htmlAttributes: new { @class = "form-control" })

<强>#UPDATE1 这是如何绑定您的下拉列表

 [HttpPost]
    public ActionResult ReportByNumber([Bind(Include = "DepartmentID")]Departments dept)
    {
    //......
    }

答案 1 :(得分:0)

在集合中使用@Html.DropDownList()时,您需要使用编辑器模板(或在每次迭代中重建SelectList,这不是非常有效)。假设你的模型是

public class ReportModel
{
  [Required(ErrorMessage = "Please select a department")]
  public string Department { get; set; }
  ....
}

然后在控制器中

public ActionResult ReportByNumber() 
{
  var departments = (from r in db.Departments select r).ToList();
  ViewBag.DepartmentList = new SelectList(departments, "Name", "Name");
  return View(reportList.ToList());
}

EditorTemplate(/Views/Shared/EditorTemplates/ReportModel.cshtml

@model ReportModel
....
@Html.LabelFor(m => m.Department)
@Html.DropDownListFor(m => m.Department, (SelectList)ViewData["DepartmentList"], "-Please select-")
@Html.ValidationMessageFor(m => m.Department)
....

主视图

@model List<ReportModel>
@using(Html.BeginForm())
{
  @Html.EditorFor(m => m, new { DepartmentList= ViewBag.DepartmentList})
  <input type="submit" />
}

注意:EditorTemplate的名称必须与模型名称匹配。您的代码建议您只想绑定到Name的{​​{1}}属性(不是ID属性),在这种情况下它可以只是

Department

答案 2 :(得分:-1)

谢谢Stephen和Feras让我走上正轨。

我最终在视图中使用了以下代码:

@Html.DropDownListFor(m => m[i].Department, (IEnumerable<SelectListItem>)ViewBag.Department, item.Department ?? "")