3

以下のコードを使用すると、コントローラーに到達したときに常に IEnumerable のbookedRooms の値が null になり、送り返したbookedRooms の数がわかりますが、RoomID と NumRooms の値は各項目で常に null です。

次のビューモデルがあります...

public class SelectDatesViewModel

    public int venueID { get; set; }
    public IEnumerable<BookedRoomViewModel> bookedRooms {get;set;}
    public string checkInDateString { get; set; }
    public int pageNo { get; set; }
    public bool showCheckIn { get; set;}
    public string startDateString { get; set; }
}
public class BookedRoomViewModel
{
    public string RoomID { get; set; }
    public string NumRooms { get; set; }
}

次のjquery ajax呼び出しを使用しています..

function showArrivalCalendar() {
    showThrobber();
    var info = {
        venueID: venueID,
        bookedRooms: getBookedRooms(),
        startDateString: $("#calendarHolder").data("arrivalstartdate"),
        checkInDateString: "",
        pageNo: 1,
        showCheckIn: true
    }
    $.ajax({
        url: "/Booking/BookingCalendar/",
        type: "POST",
        data: JSON.stringify(info),
        dataType: "json",
        success: function (retValue) {
            $("#calendarHolder").html(data);
            hideThrobber();
        }
    });
}
function getBookedRooms() {
    var bookedRooms = [];
    $("#selectBookingType").find("select").each(function () {
         if ($(this).find(":selected").val() > 0) {
            var noRooms = $(this).find(":selected").val();
            bookedRooms.push({
                    RoomID: $(this).data("roomid"),
                    NumRooms: noRooms
            });
        };
    });
    return bookedRooms;
}

このコントローラーに投稿するには..

[HttpPost]
public ActionResult BookingCalendar(SelectDatesViewModel model)
{
    return PartialView(GetBookingDates(model.venueID, model.startDateString, model.showCheckIn, model.pageNo, model.checkInDateString));
}
4

1 に答える 1

2

呼び出し$.ajaxオプションが間違っています:dataTypeサーバーに送信するデータのタイプではなく、サーバーから返されることを期待しているデータのタイプを指定するためのものです。

JSON データを送信し、モデル バインダーを正しく動作させたい場合は、contentTypeプロパティ ( JQuery docを参照) をに設定する必要があります (データも必要になる場合があります)。"application/json"JSON.stringify

したがって、正しい使用法:

$.ajax({
    url: "/Booking/BookingCalendar/",
    type: "POST",
    data: JSON.stringify(info),
    contentType: "application/json",
    success: function (retValue) {
        $("#calendarHolder").html(data);
        hideThrobber();
    }
});
于 2012-07-31T05:58:50.973 に答える