简体   繁体   中英

ASP.NET MVC Model Binding with jQuery ajax request for collection

I'm having problem with MVC3 model binding. When I post a JSON object to my controller the model binder can't bind data for the collection property. I have the following model

public class AddressListViewModel
{
public string CategoryId { get; set; }
public List<MainAddressInfo> MainAddressInfos { get; set; }
}

public class MainAddressInfo
{
public string City { get; set; }
public string Country { get; set; }
}

From the jQuery client, I am making an ajax request and sending the data

   $.ajax({
        url: '/home/MainAddressDetails',
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        data: getAddressListViewModelData(),
        success: function (data) {
            alert(data.success);
        },
        error: function () {
            alert("Error");
        }
    });

    function getAddressListViewModelData() {
    var data = {
        CategoryId: "1",
        MainAddressInfos: []
    };


    for (var i = 0; i < 2; i++) {
        var mainAddressInfo = {
            City: "NY",
            Country: "US"
        };
        data.MainAddressInfos.push(mainAddressInfo);
    }
    return JSON.stringify(data);
} 

This is my controller method I'm trying to POST to:

[HttpPost]
public ActionResult MainAddressDetails(AddressListViewModel addressInfo)
{
return Json(new { success = true });
}

I am getting the value in CaregoryId but the MainAddressInfos is always null. Can someone please let me know why binding is not happening for the collection?

尝试公开MainAddressInfos

public List<MainAddressInfo> MainAddressInfos { get; set; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM