2

我正在研究 MVC4,DropdownList 没有绑定 SelectedValue。请在下面找到我的代码,我不明白哪里出错了。

我见过 SelectList ,它有 SelectedValue 但没有在 View DropdownList 中绑定它

控制器代码

public ActionResult Edit(int id)
        {
            Employee model = _unitOfWork.EmployeeRepository.Find(id);
            ViewBag.OfficeSiteId = new SelectList(_unitOfWork.OfficeSiteRepository.Get(), "Id", "Name", model.OfficeSiteId);
return View("Edit", model);
}

看法

<div class="control-group">
                @Html.LabelFor(model => model.OfficeSiteId, new {@class = "control-label"})

                <div class="controls">
                    @Html.DropDownList("OfficeSiteId", ViewBag.OfficeSiteId as SelectList,  new {@class = "chzn-select"})
                    @Html.ValidationMessageFor(model => model.OfficeSiteId, null, new {@class = "help-inline"})
                </div>
            </div>
4

3 回答 3

2

@Html.DropDownList("OfficeSiteId",null,new {@class = "chzn-select"})

于 2013-07-23T14:18:04.050 回答
0

你的操作方法没问题。只需更改您的视图,如下所示:

<div class="control-group">
     @Html.LabelFor(model => model.OfficeSiteId, new {@class = "control-label"})

     <div class="controls">
          @Html.DropDownList("OfficeSiteId", String.Empty)

          @Html.ValidationMessageFor(model => model.OfficeSiteId)
     </div>
</div>

如果您需要设置class属性,请使用以下内容:

@Html.DropDownListFor(model => model.OfficeSiteId, 
   new SelectList(new PtDbContext().OfficeSites, "ID", "Name"),
   htmlAttributes: new { class = "yourClass" })

或者如果您通过 ViewBag 发送 selectList:

@Html.DropDownListFor(model => model.OfficeSiteId, 
    (SelectList)ViewBag.OfficeSiteId,
     htmlAttributes: new { class = "yourClass" })
于 2013-07-23T13:44:04.073 回答
0

写:

@Html.DropDownListFor(model => model.OfficeSiteId,
    ViewBag.OfficeSiteId as SelectList,  new {@class = "chzn-select"})

代替:

@Html.DropDownList("OfficeSiteId",
    ViewBag.OfficeSiteId as SelectList,  new {@class = "chzn-select"})

写:

ViewBag.OfficeSiteId = new SelectList(
    _unitOfWork.OfficeSiteRepository.Get(), "Id", "Name");

代替:

ViewBag.OfficeSiteId = new SelectList(
    _unitOfWork.OfficeSiteRepository.Get(), "Id", "Name", model.OfficeSiteId);
于 2013-07-23T13:37:17.243 回答