3
我有一個父視圖模型綁定到一個視圖,該視圖包含一個屬性,該屬性是其他視圖模型的列表。沒有爲ASP.Net MVC設置選定的值3 DropDownListFor
這裏是父視圖模型的代碼:
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中選定的值,它工作正常。我想知道爲什麼選定的值沒有綁定自動引用索引屬性。