我在Repository.cs
中有以下代码来获取Timezones
public static IEnumerable<SelectListItem> GetTimeZoneList()
{
return TimeZoneInfo.GetSystemTimeZones().Select(x => new SelectListItem()
{
Value = x.Id,
Text = x.DisplayName
});
}
我的AddEditEmployeeViewModel.cs
如下:
public class AddEditEmployeeViewModel
{
public string TimeZoneID { get; set; }
public SelectList TimeZones { get; set; }
}
并且在ajax调用中,我填写模型值如下:
public PartialViewResult GetAddEditEmployee(string id)
{
var model = new AddEditEmployeeViewModel();
model.TimeZones = new SelectList(Repository.GetTimeZoneList(), "Value", "Text");
var employee = (from e in context.tbl_users where e.eid == eid select new { e.fnamae, e.lname, e.account_status, e.preferred_timezone }).FirstOrDefault();
if (employee == null) return PartialView("_AddEditEmployee", model);
model.TimeZoneID = employee.preferred_timezone;
//model.TimeZoneID will have values like India Standard Time, UTC etc.,
//..Other properties
return PartialView("_AddEditEmp", model);
}
即使model.TimeZoneID
具有来自selectlist的匹配值,它也不会将值项保持为选中状态。我可以在SelectList
中看到从DB中获取的值。参考屏幕截图
以下是view code
@Html.DropDownListFor(m => m.TimeZoneID, Model.TimeZones, "Select a Timezone", new { @class = "selectpicker", data_width = "100%", })
我犯的错误是什么?需要进行哪些更改才能从dropdownlist/selectpicker
中选择项目?
答案 0 :(得分:2)
作为一项规则,我会替换
model.TimeZones = new SelectList(
Repository.GetTimeZoneList(),
"Value",
"Text");
与
model.TimeZones = new SelectList(
Repository.GetTimeZoneList(),
"Value",
"Text",
model.TimeZoneID);
基本上,请使用overload that takes the selected value as a parameter。您也可以简单地返回您的时区对象,而不是SelectListItems的集合:
public static IEnumerable<TimeZone> GetTimeZoneList()
{
return TimeZoneInfo.GetSystemTimeZones();
}
和
model.TimeZones = new SelectList(
Repository.GetTimeZoneList(),
"ID",
"DisplayName",
model.TimeZoneID);