使用DropDownListFor在SelectList中设置选定的值不起作用

时间:2011-09-02 00:29:37

标签: .net asp.net-mvc

我正在为下拉列表创建一个SelectList

public class EditDeviceViewModel
{
   public SelectList DeviceTypeList { get; set; }
   public int SelectedDeviceType { get; set; }

   public EditDeviceViewModel(Device device, IEnumerable<DeviceType> DeviceTypes)
   {
      ...
      DeviceTypeList = new SelectList(DeviceTypes.OrderBy(t => t.Type), 
                                      "ID", 
                                      "Type", 
                                      device.DeviceType.ID);
      SelectedDeviceType = device.DeviceType.ID;
   }
}

然后在我看来,我正在使用Html助手创建一个下拉列表

@Html.DropDownListFor(model => model.SelectedDeviceType, 
                      Model.DeviceTypeList, 
                      new { id = "devicetypelist" })

渲染视图时,未选中初始化SelectList时选择的值。我做错了什么?

2 个答案:

答案 0 :(得分:3)

DropDown列表将使用SelectedDeviceType属性的值作为选定值。您可以做的是在构造模型时设置属性值

public class EditDeviceViewModel
{
   public SelectList DeviceTypeList { get; set; }
   public int SelectedDeviceType { get; set; }

   public EditDeviceViewModel(Device device, IEnumerable<DeviceType> DeviceTypes)
   {
      ...
      DeviceTypeList = new SelectList(DeviceTypes.OrderBy(t => t.Type), 
                                      "ID", 
                                      "Type");

      SelectedDeviceType = device.DeviceType.ID;
      ...
   }
}

答案 1 :(得分:1)

DropDownListFor的第一个参数必须是保存所选值的变量。你在任何地方设置SelectedDeviceType吗?

相关问题