Setting selected value in SelectList isn't working using DropDownListFor
I am creating a SelectList for a drop down
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;
}
}
Then in my view I am creating a drop down using the Html helper
@Html.DropDownListFor(model => model.SelectedDeviceType,
Model.DeviceTypeList,
new { id = "devicetypelist" })
When the view is rendered开发者_如何学运维, the value I selected when initialising the SelectList
isn't selected. What am I doing wrong?
DropDown list will use the value of SelectedDeviceType
property as the selected value. What you can do is set the property value when you construct the model
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;
...
}
}
THe first argument to DropDownListFor must be the variable that holds your selected value. Are you setting SelectedDeviceType anywhere?
精彩评论