One out of 2 parameters are returning null

Viewed 96

I am using MVC. When I run the debugger and test with Postman and hover over the parameter, it is showing the parameter is passed a null value for MovieIds but CustomerId is working as expected.

Api Controller: newRental shows MovieIds as null when debugging

public class NewRentalsController : ApiController
{
    private ApplicationDbContext _context;

    public NewRentalsController()
    {
        _context = new ApplicationDbContext();
    }

    [HttpPost]
    public IHttpActionResult CreateNewRentals(NewRentalDto newRental)
    {
        var customer = _context.Customers.Single(c => c.Id == newRental.CustomerId);

        var movies = _context.Movies.Where(m => newRental.MovieIds.Contains(m.Id)).ToList();

        //var movies = _context.Movies.Where(m => m.Id ==1);

        foreach (var movie in movies)
        {
            if (movie.NumberAvailable == 0)
                return BadRequest("Movie is not available.");

            movie.NumberAvailable--;

            var rental = new Rental
            {
                Customer = customer,
                Movie = movie,
                DateRented = DateTime.Now
            };

            _context.Rentals.Add(rental);
        }

        _context.SaveChanges();

        return Ok();
    }

}

DTO:

public class NewRentalDto
{
    public int CustomerId { get; set; }
    public List<int> MovieIds { get; set; }
}

Postman request:

{"customerId": 2,
"movieId": 1,
"dateRented": "2017-09-28T00:00:00"
}

I think it's something to do with the List<int> because I can hard code the Id in and it will send it to the db.

1 Answers

As you correctly guessed the problem is that the MovieIds is a List<int> so your request should be like this (use brackets []):

MovieIds: [1],
Related