How to represent a month of checkboxes in an MVC model

I suggest you change you view model(s) to

public class DayVM
{
  public Day Day { get; set; }
  public bool IsSelected { get; set; }
}
public class WeekVM
{
  public WeekVM()
  {
    Days = new List<DayVM>();
    Days.Add(new DayVM() { Day = Day.Sunday });
    Days.Add(new DayVM() { Day = Day.Monday });
    .. etc
  }
  public List<DayVM> Days { get; set; }
}
public class ScheduleViewModel
{
  public ScheduleViewModel()
  {
    Weeks = new List<WeekVM>();
    Weeks.Add(new WeekVM());
    .... etc
  }
  public int PatientId { get; set; }          
  public List<WeekVM> Weeks { get; set;}          
}

Then in the view

for(int i = 0; i < Model.Weeks.Count; i++)
{
  <tr>
    <td>Week @i</td>
    for(int j = 0; j < Model.Weeks[i].Days.Count; j++)
    {
      <td>
        @Html.CheckBoxFor(m => m.Weeks[i].Days[j].IsSelected)
      </td>
    }
  </tr>
}

Side note: I don’t think you really need you own enum here – your could just use the DayOfWeek enumeration, for example Days.Add(new DayVM() { Day = DayOfWeek.Sunday });. Note also I have not included an input for the Day property since you could easily determine that from its index in the collection. In fact the Day property may not be required at all if you manually render the table header row.

Leave a Comment