我在让所选值适用于DropDownListFor时遇到一些问题。
DropDownListFor填充了一个时间列表:
// creates list of times for visit times select list
DateTime DateToday = DateTime.Today;
DateTime DateTimeStart = new DateTime(DateToday.Year, DateToday.Month, DateToday.Day, 8, 30, 0);
DateTime DateTimeEnd = new DateTime(DateToday.Year, DateToday.Month, DateToday.Day, 18, 0, 0);
List<SelectListItem> TimeFrom = new List<SelectListItem>();
while (DateTimeStart.TimeOfDay != DateTimeEnd.TimeOfDay)
{
DateTimeStart = DateTimeStart.AddMinutes(30);
TimeFrom.Add(new SelectListItem()
{
Selected = (DateTimeStart.TimeOfDay.ToString() == ViewBag.VbVisitTime),
Text = DateTimeStart.ToString("HH:mm tt"),
Value = DateTimeStart.TimeOfDay.ToString()
});
}
model.TimeFromList = new SelectList(TimeFrom, "Value", "Text");
查看
@Html.DropDownListFor(model => model.VisitDetails.VisitDateTime, Model.TimeFromList, "Select Time...", new { @class = "form-control" })
当时间= ViewBag.VbVisitTime时设置选定的值,当我调试ViewBag.VbVisitTime的值与下拉列表中的值相等时,我也显示了ViewBag.VbVisitTime的值屏幕并匹配下拉列表中的值,因此不确定为什么它不选择该值。
答案 0 :(得分:1)
上面的评论帮助我回答了我自己的问题,所以我想发布它以防万一它可以帮助其他人。
Selected
的{{1}}属性确实被忽略了,所以我在模型中创建了一个新属性。
SelectListItem
然后在我的控制器中设置它的值
public TimeSpan? VisitTimeFrom { get; set; }
然后下拉列表自动为我选择了正确的值
DateTime? visitTime = model.VisitDetails.VisitDate;
model.VisitDetails.VisitTimeFrom = visitTime.Value.TimeOfDay;