MVC4中的IEnumerable模型绑定始终为null

3
使用下面的代码后,我的IEnumerable bookedRooms在到达控制器时总是有空值,它知道我发送回了多少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));
}
1个回答

2
你的 $.ajax 调用选项是错误的: dataType 用于指定你从服务器端期望收到的数据类型,而不是你发送到服务器的数据类型。
如果你想要发送 JSON 数据,并且希望模型绑定器能正常工作,你需要设置 contentType 属性(参见JQuery文档)为"application/json"(你也可能需要使用JSON.stringify对数据进行编码)。
因此,正确的用法是:
$.ajax({
    url: "/Booking/BookingCalendar/",
    type: "POST",
    data: JSON.stringify(info),
    contentType: "application/json",
    success: function (retValue) {
        $("#calendarHolder").html(data);
        hideThrobber();
    }
});

好的,很棒,这个方法可行,但我必须使用JSON.stringify(info)(我已经更新了第一篇帖子)。谢谢nemesv。 - NoseBagUK

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接