如何在EDIT视图中使用DropDownListFor

时间:2014-04-24 13:05:35

标签: asp.net-mvc razor

我在编辑视图中遇到DropDownListFor问题。

基本上我正在使用包含我的表单的局部视图,在我的编辑和创建视图中,我称之为局部视图。

我有大约5个类似的DropdownlistFor,这些在创建动作上运行良好,但在编辑时没有,主要是我没有(无法)设置所选值。

在我的编辑操作(GET)中,如果真实对象已填充属性,则填充我的属性ViewModel。

if(icb.BAOfficer != null)
editICB.BAOfficer = icb.BAOfficer;


List<Staff> staffs = _fireService.GetAllStaffs().ToList();
staffs.Insert(0, new Staff { StaffId = -1, Name = "" });
editICB.BAOfficers = staffs;

return View(editICB);

这就是我填写下拉菜单以及我如何设置所选值的方法。

@Html.DropDownListFor(model => model.BAOfficerSelected, new SelectList(Model.BAOfficers, "StaffId", "Name", (Model.BAOfficer!= null ? Model.BAOfficer.StaffId:-1)), new { @class = "rounded indent" })
@Html.ValidationMessageFor(model => model.BAOfficer.StaffId)

3 个答案:

答案 0 :(得分:0)

我不会使用SelectList,而是经常发现使用List<SelectListItem>会更好。

此外,我通常会使用EditorTemplate作为我的下拉菜单,以保持我的观点清洁。

因此,如果我的选择列表返回List<SelectListItem>

public List<SelectListItem> BAOfficers { get; set };

您可以这样设置:

model.BAOfficers = staffs.Select(staff => 
      new SelectListItem { Text = staff.Name, Value = staff.StaffId }).ToList();

然后在EditorTemplate

<!-- EditorTempaltes\DropDownList.cshtml -->
@model System.String
<p>
    @Html.LabelFor(m => m):
    @Html.DropDownListFor(m => m, new SelectList(
        (List<SelectListItem>)ViewData["selectList"], "Value", "Text", 
        String.IsNullOrEmpty(Model) ? String.Empty : Model), String.Empty)
    @Html.ValidationMessageFor(m => m)
</p>

然后在视图中,只需将SelectList传递到EditorTemplate

@Html.EditorFor(m => m.BAOfficerSelected, "DropDownList", 
                new { selectList = Model.BAOfficers() })

答案 1 :(得分:0)

最好和最干净的方法是在SelectList对象的服务器端设置所选值。

因此,如果您的BAOfficerSelected可以为空......那就更简单了:您不需要依赖添加虚拟项来保持-1为未选择的值。

相反,你这样做:

List<Staff> staffs = _fireService.GetAllStaffs().ToList();
editICB.BAOfficers = new SelectList(staffs, "StaffId", "Name", editICB.BAOfficer != null ? editICB.BAOfficer.StaffId : null);

当然,需要将BAOfficers类型从List<Staff>更改为SelectList

然后,在您的部分视图中,您可以:

@Html.DropDownListFor(model => model.BAOfficerSelected, Model.BAOfficers, "Select one...",  new { @class = "rounded indent" })

需要添加第3个参数来指示默认值(如果未选择任何内容)是该文本。

答案 2 :(得分:0)

我解决了在编辑操作中将值设置为model.BAOfficerSelected的问题,这是(简单)秘密。

我需要第一个项目,如空选项,因为它不是必需的信息,但在编辑视图中,如果有值,我需要将其设置为选定选项。

最后,这是我的代码。

我的模特

public int BAOfficerSelected { get; set; }
public SelectList BAOfficers { get; set; }`

我的控制器创建/编辑操作

if (icb.BAOfficer != null) // only for edit action
 editICB.BAOfficerSelected = icb.BAOfficer.StaffId; //this will set the selected value like a mapping


//for Edit and Create
List<Staff> staffs = _fireService.GetAllStaffs().ToList();
staffs.Insert(0, new Staff { StaffId = -1, Name = "" });

editICB.BAOfficers = new SelectList(staffs, "StaffId", "Name");

return View(editICB);`

我的观点

@Html.DropDownListFor(model => model.BAOfficerSelected, Model.BAOfficers, new { @class = "rounded indent" })

我希望这可以帮助别人。

相关问题