2013-07-23 31 views
2

我正在使用MVC4,DropdownList没有绑定SelectedValue。请在下面找到我的代码,我不明白它出错的地方。@ Html.DropDownList没有绑定selectedValue编辑

我见过的SelectList,它的SelectedValue但鉴于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> 

回答

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); 
+0

我们同时使用DropDownList a nd DropDownListFor,我想使用DropDownList,如果我传递ViewBag.OfficeSiteId =新的SelectList(_unitOfWork.OfficeSiteRepository.Get(),“Id”,“Name”);没有任何将从我的编辑模型中选择动作 –

0

你的诉权n方法是可以的。只要改变你的观点类似如下:

<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" }) 
+1

@ Html.DropDownList(“OfficeSiteId”,String.Empty,new {class =“chzn-select”})这是错误的,编译错误,如果我写@ Html.DropDownList(“ OfficeSiteId“,ViewBag.OfficeSiteId作为SelectList,String.Emp喜欢这个,没有选择dropdlown,我需要选择model.OfficeSiteid值 –

+0

对不起,你是对的我已经编辑了我的答案代码...这将工作 – AminSaghi

+0

,但我怎么能通过类名新{@class =“chzn-select”} –

1

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