Reputation: 137
I'm not able to populate nested objects when I send a Json with AJAX JQuery.
Specifically I can't populate LineItems.
LineItems is a list of different type of object: can be website or campaign, so on my server side I created two classes (website/campaign) that inherit from a generic product class.
The json format is what the client send me via post, so I want to figured out how to bind automatically (or not) my c# objects with the json that I received.
In the controller, the result until now is the Order populated with his own properties, but the branch of LineItems is always a product without values.
Thanks a lot!
MODELS
public class Order
{
public string Partner { get; set; }
public string OrderID { get; set; }
public List<LineItems> LineItems { get; set; }
}
public class LineItems
{
public Product Product = new Product();
}
public class Product
{
public string ID { get; set; }
public string Category { get; set; }
}
public class Website : Product
{
public WebsiteDetails WebsiteDetails = new WebsiteDetails();
}
public class WebsiteA : Website
{
public string ContactName { get; set; }
}
public class PaidSearch : Product
{
public Campaign Campaign = new Campaign();
}
public class Campaign
{
public string CampaignName { get; set; }
}
public class WebsiteDetails
{
public string TemplateId { get; set; }
public string WebsiteBusinessName { get; set; }
}
CONTROLLER
[HttpPost("rec-order")]
public JsonResult Post([FromForm]Order order)
{
return Json(new { order = order });
}
JQUERY
jQuery.ajax({
url: "/api/rec-order",
type: "POST",
dataType: 'json',
data: {
"Partner": "TNT",
"OrderID": "999888777",
"LineItems": [
{
"ID": 1,
"Category": "First Category Website",
"WebsiteDetails": {
"TemplateId": "12",
"WebsiteBusinessName": "Lorem Ipsum",
}
},
{
"ID": 1,
"Category": "First Category Campaign",
"Campaign": {
"CampaignName": "Lorem Ipsum",
}
}
]
},
success: function (data) {
console.log(data);
}
});
Upvotes: 1
Views: 382
Reputation: 46239
Your LineItems
class need to contain int ID
,string Category
... properties, not an object.
You can try this to instead of your current Models
public class WebsiteDetails
{
public string TemplateId { get; set; }
public string WebsiteBusinessName { get; set; }
}
public class Campaign
{
public string CampaignName { get; set; }
}
public class LineItem
{
public int ID { get; set; }
public string Category { get; set; }
public WebsiteDetails WebsiteDetails { get; set; }
public Campaign Campaign { get; set; }
}
public class Order
{
public string Partner { get; set; }
public string OrderID { get; set; }
public List<LineItem> LineItems { get; set; }
}
Upvotes: 1