I have a booking app, which accepts a single “booking” object, and works ok. My question is, how do I convert this to accept multiple records (from JSON):
Booking.cs
namespace MvcApplication4.Models
{
public class Booking
{
[Key()]
public long ID { get; set; }
public long? HID { get; set; }
public long RID { get; set; }
public string Occ { get; set; }
public DateTime CI { get; set; }
public DateTime CO { get; set; }
public long? CID { get; set; }
}
}
BookingsContext.cs
namespace MvcApplication4.Models
{
public class BookingsContext : DbContext
{
public BookingsContext() : base("name=BookingsContext")
{
}
public DbSet<Booking> Bookings { get; set; }
}
}
BookingsController.cs
// POST api/Bookings
public HttpResponseMessage PostBooking(Booking booking)
{
if (ModelState.IsValid)
{
// Add the booking
db.Bookings.Add(booking);
db.SaveChanges();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, booking);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = booking.RID }));
return response;
}
}
The JSON currently passed is:
var comment = {ID:0, HID: $('#HID').val(), RID:$('#RID').val(), Occ:$('#Occ').val(), CI:$('#CI').val(), CO:$('#CO').val(), CID:$('#CID').val()},{ID:0, HID: $('#HID').val(), RID:$('#RID').val(), Occ:$('#Occ').val(), CI:$('#CI').val(), CO:$('#CO').val(), CID:$('#CID').val()};
How can I pass multiple records to the controller, so that I don’t have to call the JSON Post method may times?
You could modify the signature of your action to take an array of Booking:
and then send an array of booking from the client: