Reputation: 114
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!
Upvotes: 2
Views: 2917
Reputation: 10429
Your json should be like
var vJson = {
"Guid": "ccda117f-a9b5-4f54-ab4a-07a9cf403ef7",
"Shops": [
{ "Name": "Shop1", "Acronym": "ACRO1" },
{ "Name": "Shop2", "Acronym": "ACRO2" },
{ "Name": "Shop3", "Acronym": "ACRO3" },
{ "Name": "Shop4", "Acronym": "ACRO4" }
]
};
and your message class should be
public class message
{
public string Guid { get; set; }
public Ilist<shop> Shops { get; set; }
}
then you can loop like
foreach(var shop in postmessage.Shops)
{
//some code
}
Note:-your naming convention is not ok class name should be in Passcal case like message should be Message and in javascript you should use camel case like Guid should be guid.
Upvotes: 1