Search code examples
c#asp.netasp.net-mvcasp.net-corerazor

value cannot be null: _context.Add(models.Reservations.FirstOrDefault());


I'm getting the error:

ArgumentNullException: Value cannot be null. (Parameter 'source')

Here is the code for my action where I'm getting the error from:

[HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create(Models.Models models)
    {
        if (ModelState.IsValid)
        {
            _context.Add(models.Reservations.FirstOrDefault());
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        return View(models);
    }

Here is my models class:

public class Models
{
    public IEnumerable<ReservationsModel> Reservations { get; set; }
    public IEnumerable<RoomsModel> Rooms { get; set; }
}

This is an example of how I get the values from the View:

<select asp-for="Reservations.FirstOrDefault().RoomId" class="form-select" aria-label="Default select example">
        @foreach (var item in Model.Rooms)
        {
            <option asp-for="Reservations.FirstOrDefault().RoomId" value="@Html.DisplayFor(modelItem => item.RoomID)">@Html.DisplayFor(modelItem => item.RoomID)</option>
        }
</select>

And finally my GET method in case you need it:

public async Task<IActionResult> Create()
{
    var obj = new Models.Models
    {
        Reservations = await _context.Reservations.ToListAsync(),
        Rooms = await _context.Rooms.ToListAsync()
    };
    return View(obj);
}

Solution

  • I solved the isse by myself! It was really simple!!! Just created another property in the Models class of the same type, but instead of IEnumerable it was just of type ReservationsModel:

    public class Models
    {
        public IEnumerable<ReservationsModel> Reservations { get; set; }
        public ReservationsModel Reservations2 { get; set; }
        public IEnumerable<RoomsModel> Rooms { get; set; }
    }
    

    and used it to pass the data from the View to the Controller. Thanks to anyone that responded to my question!