0

我有一个预订应用程序,它接受一个“预订”对象,并且工作正常。我的问题是,如何将其转换为接受多个记录(来自 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;
                }
            }

当前传递的 JSON 是:

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()};

如何将多条记录传递给控制器​​,这样我就不必多次调用 JSON Post 方法?

4

1 回答 1

3

您可以修改您的操作签名以进行预订数组:

public HttpResponseMessage PostBooking(Booking[] bookings)
{
    ...
}

然后从客户端发送一系列预订:

var bookings =
    [
        {
            ID: 0,
            HID: 'hid1',
            RID: 'rid1',
            Occ: 'occ1',
            CI: 'ci1',
            CO: 'co1',
            CID: 'cid1'
        },
        {
            ID: 1,
            HID: 'hid2',
            RID: 'rid2',
            Occ: 'occ2',
            CI: 'ci2',
            CO: 'co2',
            CID: 'cid2'
        }
    ];
于 2012-06-14T15:24:50.833 回答