I’m looking to bind a JSON object to a List nested in an object.
Background
I have a Category class that contains a list of 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()
{
}
}
The user can select a number of Funds per Category, and then I want to POST a JSON string back to my Controller and have the ModelBinder bind the JSON to the object model.
This is my Action method:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Category category)
{
// Categoy.Id & Categoy.CountryID is populated, but not Funds is null
return Json(true); //
}
So far, I have this 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");
});
But this isn’t working. The properties of Category are populated, but the List<ConfigurationFund>() isn’t being populated.
Question
How do I need to modify this to get it to work?
Supplementary Info
Just to note, I’ve also tried to post the Category & ConfiguredFunds separately, and it works, with something similar to the following:
$('#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");
});
In the following Action method, the ConfiguredFunds are populated, and the Category is also populated. However, the Category’s List isn’t populated. I need the Category & its List to be populated.
public ActionResult Edit(List<ConfigurationFund> configuredFunds, Category category)
{
return Json(true);
}
I’ve figured it out. I just needed to change
to:
Basically, I just specified that the
fundsbelong to aCategorywithdata["category.funds"]