How to represent a month of checkboxes in an MVC model

前端 未结 1 921
时光取名叫无心
时光取名叫无心 2020-12-02 01:11

I can\'t manage to get my head around how to use MVC to create the following table, and successfully bind it to a model:

相关标签:
1条回答
  • 2020-12-02 01:49

    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.

    0 讨论(0)
提交回复
热议问题