我有一个父视图模型绑定到一个视图,该视图包含一个属性,该属性是其他视图模型的列表。
以下是父视图模型代码:
var timeAvailability = (from u in _entities.UserTimeAvailabilities
where u.UserId == userId
select u).ToList();
for(int index = 0; index < timeAvailability.Count; index++)
{
var availableTime = timeAvailability[index];
TimeAvailability.Add(new AvailableTimeSlotViewModel(index)
{
SelectedDay = availableTime.DayId,
SelectedStartTime = availableTime.StartHourId.HasValue ? availableTime.StartHourId.Value : 0,
SelectedEndTime = availableTime.EndHourId.HasValue ? availableTime.EndHourId.Value : 0
});
}
TimeAvailability是一个列表
这是AvailableTimeSlotViewModel:
public List<SelectListItem> Days { get; set; }
public int Index { get; set; }
public List<SelectListItem> Hours { get; set; }
[Display(Name = "Select Day")]
public int SelectedDay { get; set; }
[Display(Name="Start Time")]
public int SelectedStartTime { get; set; }
[Display(Name = "End Time")]
public int SelectedEndTime { get; set; }
public AvailableTimeSlotViewModel(int index)
{
Index = index;
_entities = Repository.GetRepository();
Days = new List<SelectListItem>();
_entities.Days.ToList().ForEach(d => Days.Add(new SelectListItem { Value = d.DayId.ToString(), Text = d.Name }));
Hours = new List<SelectListItem>();
_entities.Hours.ToList().ForEach(h => Hours.Add(new SelectListItem { Value = h.HourId.ToString(), Text = h.Name }));
}
视图中与UserPreferences绑定的代码:
<div id="time-availability-div">
@for (int index = 0; index < Model.TimeAvailability.Count; index++)
{
<table>
<thead>
<tr>
<td>
@Html.LabelFor(m => m.TimeAvailability[index].SelectedDay)
</td>
<td>
@Html.LabelFor(m => m.TimeAvailability[index].SelectedStartTime)
</td>
<td>
@Html.LabelFor(m => m.TimeAvailability[index].SelectedEndTime)
</td>
</tr>
</thead>
<tbody>
<tr>
<td>
@Html.DropDownListFor(m => m.TimeAvailability[index].SelectedDay, Model.Days)
</td>
<td>
@Html.DropDownListFor(m => m.TimeAvailability[index].SelectedStartTime, Model.Hours)
</td>
<td>
@Html.DropDownListFor(m => m.TimeAvailability[index].SelectedEndTime, Model.Hours)
</td>
</tr>
</tbody>
</table>
}
</div>
需要注意的一点是,如果我在DropDownListFor中显式设置选定的值,它可以正常工作。我想知道为什么所选值不会自动引用索引处的属性。
答案 0 :(得分:1)
我想知道为什么所选择的值不会自动引用索引处的属性。
因为您使用复杂的集合lambda表达式作为第一个参数:m => m.TimeAvailability[index].SelectedEndTime
。不幸的是,DropDownListFor
助手不支持自动设置此类复杂表达式的默认值,您需要设置所选值:
@Html.DropDownListFor(
m => m.TimeAvailability[index].SelectedEndTime,
new SelectList(Model.Hours, "Value", "Text", Model.TimeAvailability[index].SelectedEndTime)
)