В методе HttpPost есть две ошибки: ArgumentNullException и NullReferenceException. Я хочу связать Id выбранных флажков из представления и отправить их в BookingsViewModel. Затем каждый выбранный флажок будет генерировать запись бронирования, когда я нажимаю кнопку отправки.
Метод HttpGet:
[HttpGet]
public ActionResult TestTimeSlot(Booking booking)
{
IEnumerable<Booking> _booking = _context.Bookings
.Where(b => b.RoomId == booking.RoomId)
.Where(b => b.BookDate == booking.BookDate)
.Include(b => b.Building)
.Include(b => b.Room)
.Include(b => b.TimeSlot)
.OrderBy(b => b.TimeSlotId)
.ToList();
IEnumerable<TimeSlot> _timeSlot = _context.TimeSlots.ToList();
foreach (var slot in _timeSlot)
{
foreach(var book in _booking)
{
if (slot.Id != book.TimeSlotId)
{
slot.IsBooked = false;
}
else
{
slot.IsBooked = true;
break;
}
}
}
var viewModel = new BookingsViewModel
{
TimeSlotList = _timeSlot,
BuildingId = booking.BuildingId,
RoomId = booking.RoomId,
BookDate = booking.BookDate
};
return View(viewModel);
}
Метод HttpPost:
[HttpPost]
public ActionResult TestTimeSlot(BookingsViewModel bookingsViewModel)
{
if (bookingsViewModel.TimeSlotList.Count(x => x.IsSelected) == 0) //error here:
//ArgumentNullException: Value
//cannot be null. (Parameter
//'source')
{
//here, return an error that "none is selected"
return RedirectToAction("TestTimeSlot", "Bookings");
}
else
{
foreach (var timeSlot in bookingsViewModel.TimeSlotList) //error here: NullReferenceException:
//Object reference not set to an
//instance of an object.
{
if (timeSlot.IsSelected == true)
{
var booking = new Booking
{
BuildingId = bookingsViewModel.BuildingId,
RoomId = bookingsViewModel.RoomId,
BookDate = bookingsViewModel.BookDate,
TimeSlotId = timeSlot.Id
};
_context.Bookings.Add(booking);
}
}
_context.SaveChanges();
return RedirectToAction("Index", "Bookings");
}
}
В представлениях TestTimeSlot.cs html
<tbody>
@foreach (var slot in Model.TimeSlotList)
{
if (slot.IsBooked == true)
{
<tr bgcolor="ECECEC" class="text-muted"> @* gray out row background and text *@
<td>
@Html.CheckBoxFor(modelItem => slot.IsSelected, new { @disabled = "" })
</td>
<td>
@Html.DisplayFor(modelItem => slot.StartTime)
</td>
<td>
@Html.DisplayFor(modelItem => slot.EndTime)
</td>
</tr>
}
else
{
<tr>
<td>
@Html.HiddenFor(modelItem => slot.Id) @* to store selected time slot's Id? *@
@Html.CheckBoxFor(modelItem => slot.IsSelected)
</td>
<td>
@Html.DisplayFor(modelItem => slot.StartTime)
</td>
<td>
@Html.DisplayFor(modelItem => slot.EndTime)
</td>
</tr>
}
}
</tbody>