我正在填充下拉菜单,如下所示:
@Html.DropDownListFor(model => model.timeSlot, new SelectList(ViewBag.TimeSlots, "id", "timeSlot"), "")
来自这里:
private CPVIPPreviewTimeSlots dbTimeSlots = new CPVIPPreviewTimeSlots();
ViewBag.TimeSlots = dbTimeSlots.Data.ToList();
来自这里:
public class CP_VIP_Preview_TimeSlots
{
public int id { get; set; }
[DisplayName("Time Slots")]
public string timeSlot { get; set; }
[DisplayName("Date Slots")]
public string dateSlot { get; set; }
}
public class CPVIPPreviewTimeSlots : DbContext
{
public DbSet<CP_VIP_Preview_TimeSlots> Data { get; set; }
}
现在我正在调整此下拉菜单,因此它同时具有timeSlot和dateSlot:
@Html.DropDownListFor(model => model.timeSlot, new SelectList(ViewBag.TimeSlots, "id", "dateSlot timeSlot"), "")
但是我收到了这个错误:
does not contain a property with the name 'dateSlot timeSlot'.
我可以同时拥有1个下拉列表吗?我希望这是有道理的。
答案 0 :(得分:0)
您需要稍微更改源,因为SelectList需要单个字段的名称。但是你可以轻松地使用LINQ的选择:
ViewBag.TimeSlots.Select(ts => new {
Id = ts.id,
Text = ts.dateSlot + " " + ts.timeSlot
})
这就是你给SelectList的东西。确保现在提供新属性的名称,并将列表转换为具体类型:
new SelectList(
((IEnumerable<TimeSlot>)ViewBag.TimeSlots).Select(ts => new {
Id = ts.id,
Text = ts.dateSlot + " " + ts.timeSlot
}),
"Id", "Text")