我的目标是遍历我的词典中的所有日子,所以我不必每天都有明确的清单。如果我这样做,将会有很多重复。
我制作了一个包含字典作为属性的模型,如下所示:
public class ReWeekRowModel()
{
public Dictionary<DayOfWeek, ReDayModel> Days { get; set; }
}
上面的ReDayModel类只包含属性Hours和Comments。 以下是模型的构造函数:
public ReWeekRowModel()
{
Id = ReChronoModels.RandNum.Next(100);
CreatedDate = DateTime.Now;
Days = new Dictionary<DayOfWeek, ReDayModel>
{
{DayOfWeek.Monday, new ReDayModel()},
{DayOfWeek.Tuesday, new ReDayModel()},
{DayOfWeek.Wednesday, new ReDayModel()},
{DayOfWeek.Thursday, new ReDayModel()},
{DayOfWeek.Friday, new ReDayModel()},
{DayOfWeek.Saturday, new ReDayModel()},
{DayOfWeek.Sunday, new ReDayModel()}
};
}
我在发布时预先填充了几个ReWeekRowModel,并从索引页面点击了编辑链接(这是基于visual studio中提供的解决方案)。 我设法在编辑页面中正确显示数据。
@foreach (KeyValuePair<DayOfWeek, ReDayModel> day in Model.Days)
{
@Html.Label(day.ToString(), htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-1">
@Html.EditorFor(model => model.Days[day.Key].Hours, new {htmlAttributes = new {@class = "form-control"}})
@Html.ValidationMessageFor(model => model.Days[day.Key].Hours, "", new {@class = "text-danger"})
</div>
@Html.Label("Comments:", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-7">
@Html.EditorFor(model => model.Days[day.Key].Comments, new {htmlAttributes = new {@class = "form-control"}})
@Html.ValidationMessageFor(model => model.Days[day.Key].Comments, "", new {@class = "text-danger"})
</div>
}
工作正常,并向我显示包含日的时间和评论。
但是当我尝试使用PostBack时,它会尝试使用键作为字符串进行更新,而不是DayOfWeek。
在Chrome中调试时:
这会导致索引页面崩溃:
Line 99: <td class="hidden-md hidden-sm hidden-xs">
Line 100: @Html.DisplayFor(modelItem =>item.Days[DayOfWeek.Monday].Hours)
Line 101: </td>
我知道我可以通过使用字符串版本作为键来避免这种情况,但我想使用DayOfWeek枚举!
是否有可能以简单的方式,或者我应该只使用字符串作为键?