My aim is to loop through all the days in my dictionary so I don't have to explicity list every day. As well as if I do that, there will be a lot of duplicate.
I've made a model containing a dictionary as a property like this:
public class ReWeekRowModel()
{
public Dictionary<DayOfWeek, ReDayModel> Days { get; set; }
}
The ReDayModel class above, only contains the properties Hours and Comments. Here is the constructor for the model:
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()}
};
}
I'm prepopulating a couple of ReWeekRowModel at launch, and from the index page, i click the edit link (this is based on the shipped solution in visual studio). I manage to get the data showing correctly in the edit page.
@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>
}
Works fine, and shows me the Hours and Comments of the containing day.
But when I try to do the PostBack it tries to update with the key as a string, not as a DayOfWeek.
When debugging in Chrome:
- Days[Monday].Hours:5.5
- Days[Monday].Comments:Working hard
- Days[Tuesday].Hours:5.5
- Days[Tuesday].Comments:Done with work n stuff
- Days[Wednesday].Hours:2
- Days[Wednesday].Comments:
- Days[Thursday].Hours:0
- Days[Thursday].Comments:
- Days[Friday].Hours:0
- Days[Friday].Comments:
- Days[Saturday].Hours:0
- Days[Saturday].Comments:
- Days[Sunday].Hours:0
- Days[Sunday].Comments:
This results in a crash at the index page:
Line 99: <td class="hidden-md hidden-sm hidden-xs">
Line 100: @Html.DisplayFor(modelItem =>item.Days[DayOfWeek.Monday].Hours)
Line 101: </td>
I know I can circumvent this by just using the string version as key instead, but I want to use the the DayOfWeek enum!
Is it possible in an easy way, or should I just use string as the key?