gpt4 book ai didi

asp.net - 未为 ASP.Net MVC 3 DropDownListFor 设置所选值

转载 作者:行者123 更新时间:2023-12-02 10:10:50 25 4
gpt4 key购买 nike

我有一个父 View 模型绑定(bind)到一个 View ,该 View 包含一个属性,该属性是其他 View 模型的列表。

这是父 View 模型代码:

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
});
}

可用时间是一个列表

这是可用的TimeSlotViewModel:

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 }));
}

View 中绑定(bind)到 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 中显式设置所选值,它就可以正常工作。我想知道为什么所选值没有自动绑定(bind)引用索引处的属性。

最佳答案

I'm wondering why the selected value isn't bound automatically referencing the property at index.

因为您使用了复杂的集合 lambda 表达式作为第一个参数:m => m.TimeAvailability[index].SelectedEndTime。不幸的是,DropDownListFor 帮助器不支持自动设置此类复杂表达式的默认值,您需要设置选定的值:

@Html.DropDownListFor(
m => m.TimeAvailability[index].SelectedEndTime,
new SelectList(Model.Hours, "Value", "Text", Model.TimeAvailability[index].SelectedEndTime)
)

关于asp.net - 未为 ASP.Net MVC 3 DropDownListFor 设置所选值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9254754/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com