MVC传递列表以查看对象引用错误

时间:2015-02-09 11:19:06

标签: c# asp.net-mvc

我有以下视图模型结构:

public class ClubViewModel
{
    public int ClubId { get; set; }
    public IList<CalendarEntryViewModel> MeetingDays { get; set; }          
    public string AdditionalInfo { get; set; }
}

 public class CalendarEntryViewModel
{
    public Days Day { get; set; }
    [DataType(DataType.Time)]
    public DateTime? From { get; set; }
    [DataType(DataType.Time)]
    public DateTime? To { get; set; }        
}

我正在尝试将 CREATE 视图添加到我的项目中,该视图将容纳该列表,并为我提供周一至周日的选项。

我已将以下内容添加到“我的创建”视图中:

@for (int meetingDay = 0; meetingDay < Model.MeetingDays.Count; meetingDay++)
{
    @* Get the current day of week *@
    var dayOfWeek = Enum.GetName(typeof(DayOfWeek), meetingDay);

    <label>@dayOfWeek Start</label>
    @Html.TextBoxFor(m => Model.MeetingDays[meetingDay].From)
    <label>@dayOfWeek Finish</label>
    @Html.TextBoxFor(m => Model.MeetingDays[meetingDay].To)
}

我的控制器看起来像这样:

public ActionResult CreateNew()
{

    ClubViewModel viewModel = new ClubViewModel();

viewModel.MeetingDays = new List();

    viewModel.MeetingDays.Add(new CalendarEntryViewModel { Day = Days.Monday });
    viewModel.MeetingDays.Add(new CalendarEntryViewModel { Day = Days.Tuesday });
    viewModel.MeetingDays.Add(new CalendarEntryViewModel { Day = Days.Wednesday });
    viewModel.MeetingDays.Add(new CalendarEntryViewModel { Day = Days.Thursday });
    viewModel.MeetingDays.Add(new CalendarEntryViewModel { Day = Days.Friday });
    viewModel.MeetingDays.Add(new CalendarEntryViewModel { Day = Days.Saturday });
    viewModel.MeetingDays.Add(new CalendarEntryViewModel { Day = Days.Sunday });

    return View(viewModel);
}

我试图在一周中的每一天传递给我的观点,以便用户能够提供每天的往返,但是我得到了:

  

对象引用未设置为对象的实例。

1 个答案:

答案 0 :(得分:3)

您应该创建列表MeetingDays的实例,然后在列表中添加项目:

public ActionResult CreateNew()
{

    ClubViewModel viewModel = new ClubViewModel();

    viewModel.MeetingDays = new List<CalendarEntryViewModel>();

    viewModel.MeetingDays.Add(new CalendarEntryViewModel { Day = Days.Monday });
    viewModel.MeetingDays.Add(new CalendarEntryViewModel { Day = Days.Tuesday });
    viewModel.MeetingDays.Add(new CalendarEntryViewModel { Day = Days.Wednesday });
    viewModel.MeetingDays.Add(new CalendarEntryViewModel { Day = Days.Thursday });
    viewModel.MeetingDays.Add(new CalendarEntryViewModel { Day = Days.Friday });
    viewModel.MeetingDays.Add(new CalendarEntryViewModel { Day = Days.Saturday });
    viewModel.MeetingDays.Add(new CalendarEntryViewModel { Day = Days.Sunday });

    return View(viewModel);
}