Как связать JSON с объектом и вложенным списком? - PullRequest
0 голосов
/ 02 декабря 2011

Я хочу привязать объект JSON к списку, вложенному в объект.

Фон

У меня есть класс Category, который содержит списокиз ConfigurationFunds:

public class Category
{
    public int Id { get; set; }
    public string CountryId { get; set; }
    public string Name { get; set; }

    public List<ConfigurationFund> Funds { get; set; }

    public Category()
    {
        Funds = new List<ConfigurationFund>();
    }
}

public class ConfigurationFund 
{
    public int Id { get; set; }
    public string CountryId { get; set; }
    public string Name { get; set; }

    public ConfigurationFund()
    {

    }
}

Пользователь может выбрать количество фондов в категории, а затем я хочу отправить строку JSON обратно в мой контроллер и заставить ModelBinder связать JSON с объектной моделью.

Это мой метод действия:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Category category) 
{
    // Categoy.Id & Categoy.CountryID is populated, but not Funds is null
    return Json(true); // 
}

Пока у меня есть этот jQuery:

$('#Save').click(function (e) {
    e.preventDefault();

    var data = {};

    data["category.Id"] = $('#CategorySelector').find(":selected").val();
    data["category.countryId"] = $('#CategorySelector').find(":selected").attr("countryId");

    var funds = {};
    $('#ConfiguredFunds option').each(function (i) {
        funds["funds[" + i + "].Id"] = $(this).val();
        funds["funds[" + i + "].countryId"] = $(this).attr("countryId");
    });

    data["category.funds"] = funds;

    $.post($(this).attr("action"), data, function (result) {
        // do stuff with response
    }, "json");
});

Но это не работает.Свойства категории заполняются, но List<ConfigurationFund>() не заполняется.

Вопрос

Как мне изменить это, чтобы заставить его работать?

Дополнительная информация

Просто чтобы заметить, я также пытался опубликовать Category & ConfiguredFunds отдельно, и он работает примерно так:

$('#Save').click(function (e) {
    e.preventDefault();

    var data = {};

    data["category.Id"] = $('#CategorySelector').find(":selected").val();
    data["category.countryId"] = $('#CategorySelector').find(":selected").attr("countryId");

    $('#ConfiguredFunds option').each(function (i) {
        data["configuredFunds[" + i + "].Id"] = $(this).val();
        data["configuredFunds[" + i + "].countryId"] = $(this).attr("countryId");
    });

     $.post($(this).attr("action"), data, function (result) {
        // do stuff with response
    }, "json");
});

В следующем методе Action заполняются ConfiguredFunds,и категория также заполнена.Однако список категорий не заполнен .Мне нужна категория и ее список для заполнения.

public ActionResult Edit(List<ConfigurationFund> configuredFunds, Category category)
{
    return Json(true);
}

1 Ответ

0 голосов
/ 02 декабря 2011

Я понял это. Мне просто нужно изменить

data["category.Id"] = $('#CategorySelector').find(":selected").val();
data["category.countryId"] = $('#CategorySelector').find(":selected").attr("countryId");

var funds = {};
$('#ConfiguredFunds option').each(function (i) {
    funds["funds[" + i + "].Id"] = $(this).val();
    funds["funds[" + i + "].countryId"] = $(this).attr("countryId");
});

data["category.funds"] = funds;

$.post($(this).attr("action"), data, function (result) {
    // do stuff with response
}, "json");

до:

data["category.Id"] = $('#CategorySelector').find(":selected").val();
data["category.countryId"] = $('#CategorySelector').find(":selected").attr("countryId");

$('#ConfiguredFunds option').each(function (i) {
    data["category.funds[" + i + "].Id"] = $(this).val();
    data["category.funds[" + i + "].countryId"] = $(this).attr("countryId");
});

$.post($(this).attr("action"), data, function (result) {
    // do stuff with response
}, "json");

По сути, я только что указал, что funds принадлежит Category с data["category.funds"]

...