@ Html.DropDownList未绑定Edit中的selectedValue

时间:2013-07-23 13:31:38

标签: asp.net-mvc asp.net-mvc-4

我正在研究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>

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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);

答案 2 :(得分: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" })