MVC DropDownListFor未被选择的值
本文关键字:选择 DropDownListFor MVC | 更新日期: 2023-09-27 18:18:02
我有一些问题,使所选值为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在屏幕上并匹配下拉列表中的值,所以不确定为什么它不选择值
上面的评论帮助我回答了我自己的问题,所以我想我就把它贴出来,以防它对其他人有帮助。
SelectListItem
的Selected
属性确实被忽略了,所以我在模型中创建了一个新属性。
public TimeSpan? VisitTimeFrom { get; set; }
然后在控制器中设置这个的值
DateTime? visitTime = model.VisitDetails.VisitDate;
model.VisitDetails.VisitTimeFrom = visitTime.Value.TimeOfDay;
然后下拉列表自动为我选择正确的值
@Html.DropDownListFor(model => model.VisitDetails.VisitTimeFrom, Model.TimeFromList, "Select Time...", new { @class = "form-control" })