I'm trying to have an array of pairs of string (key/value), here (name/acronym), and trying to loop in these 5 pairs.
My jquery ajax is this one:
var vJson = {
"Guid": "ccda117f-a9b5-4f54-ab4a-07a9cf403ef7",
"Donnees":
{
"Shops":
[
{ "Name": "Shop1", "Acronym": "ACRO1" },
{ "Name": "Shop2", "Acronym": "ACRO2" },
{ "Name": "Shop3", "Acronym": "ACRO3" },
{ "Name": "Shop4", "Acronym": "ACRO4" }
]
}
};
$.ajax({
url:"https://www.mywebsite.net/api/Create",
data: vJson,
type:"POST",
dataType: 'json',
success: function(data) {
console.log(data);
}
}
);
My c# controller is
public class ShopController : Controller
{
[HttpPost]
public string Create(message postMessage)
{
string guid = postMessage.Guid;
(...)
}
}
The objects are
public class message
{
public string Guid { get; set; }
public shop Shops { get; set; }
}
public class shop
{
public string Name { get; set;}
public string Acronym { get; set;}
}
In the controller, when I ask for the guid, it works perfectly (in the code).
However, I don't know how to create an array of elements [Shop1/ACRO1, Shop2/ACRO2...] and how to loop through this array? I tried postMessage.Donnees.Shops[0].Name.ToString but without any success. I think I miss an object Shops in my code but how to insert it in the other object?
I think at a point, I have to create a Dictionary object but where and how do I do that?
So my main problem is that nested array of objects in json. PLEASE, someone can put me on the tracks? It would be really appreciated!
messagemodel needs a property nameDonneeswhich is a model containing a property namedShops. You also needdata: JSON.stringify(vJson)and addcontentType: 'application/json',Donneesinmessageclass. You need to have c# class reflecting the same structure of json you are sending from client.