2016-08-14 91 views
-2

的selectedItem属性我有下面的代码在Repository.cs来获取TimezonesMVC选择列表的不显示在下拉

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); 
} 

夏娃n虽然model.TimeZoneID与获取的选择列表具有匹配的值,但它不会将值项保留为选定状态。我可以看到SelectList中DB的值。截图以供参考

SelectList items

这里是view code

@Html.DropDownListFor(m => m.TimeZoneID, Model.TimeZones, "Select a Timezone", new { @class = "selectpicker", data_width = "100%", }) 

有什么错误我犯在这里。需要做什么修改才能从dropdownlist/selectpicker中选择该项目?

+0

你在'model.TimeZoneID'有效值返回局部视图之前? – Shyju

+0

是的,我这样做,正如上面代码中提到的那样.. @Shyju –

+2

你的代码看起来非常好。这里是我从你的代码中创建的一个工作示例https://dotnetfiddle.net/FiIEOf – Shyju

回答

1

作为一个规则,我会

model.TimeZones = new SelectList(
    Repository.GetTimeZoneList(), 
    "Value", 
    "Text", 
    model.TimeZoneID); 

更换

model.TimeZones = new SelectList(
    Repository.GetTimeZoneList(), 
    "Value", 
    "Text"); 

基本上,使用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); 
+0

中的一个值仍然没有运气,它的代码应该可以正常工作。它作为'Nothing Selected'出现.. –

+0

@GuruprasadRao为了消除显而易见的原因:做了你重建? –

+0

是的..我没有..再次运气.. :( –

相关问题