1

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?

1 Answer 1

1

Try making MainAddressInfos public:

public List<MainAddressInfo> MainAddressInfos { get; set; }
Sign up to request clarification or add additional context in comments.

1 Comment

yeah, I guess I missed the modifier. Thanks for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.