I have a ASP.NET API that expects a string model:
[HttpPost]
public ActionResult Add(string model)
{
var m = JsonConvert.DeserializeObject<CustomModel>(model);
...
}
So far, I have been doing this to pass data to it:
var addModel = {
"SomeValue": {
"Some": "example",
"Value": "example"
},
"AnotherValue": "example"
}
var model = JSON.stringify(addModel);
And it works just fine. But now I need to ship data this way:
var addModel = {
"SomeValue": {
"Some": "example",
"Value": "example"
},
"AnotherValue": "example",
"MyArray[0].SomeValue": 1,
"MyArray[0].AnotherValue": a,
"MyArray[1].SomeValue": 1,
"MyArray[1].AnotherValue": a,
}
How do I add MyArray to the object so it can be passed to the back-end in the proper format?
asked Aug 18, 2016 at 12:44
Glenn Utter
2,3637 gold badges32 silver badges45 bronze badges
4 Answers 4
Just declare it as an array like so
var addModel = {
"SomeValue": {
"Some": "example",
"Value": "example"
},
"AnotherValue": "example",
"MyArray": [
{ "SomeValue" : 1, "AnotherValue": a },
{ "SomeValue" : 1, "AnotherValue": a }
]
}
answered Aug 18, 2016 at 12:47
deadwards
2,1381 gold badge16 silver badges29 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
"MyArray": [
{
"SomeValue": 1,
"AnotherValue": a
},
{
"SomeValue": 1,
"AnotherValue": a
}
]
answered Aug 18, 2016 at 12:47
adam-beck
6,0295 gold badges22 silver badges35 bronze badges
Comments
You can put them in directly with
addModel.MyArray[0] = { "SomeValue" : 1, "AnotherValue": a };
You can push into the array with
addModel.MyArray.push( { "SomeValue" : 1, "AnotherValue": a });
after addModel is declared
answered Aug 18, 2016 at 12:55
Mark Schultheiss
34.3k13 gold badges75 silver badges117 bronze badges
Comments
var myArray = [
{
"a":1,
"b":2
},
{
"a":1,
"b":2
}
];
var addModel = {
"SomeValue": {
"Some": "example",
"Value": "example"
},
"AnotherValue": "example",
"myArray": myArray
};
Michael Parker
13k7 gold badges42 silver badges58 bronze badges
answered Aug 18, 2016 at 12:49
black_pottery_beauty
8798 silver badges17 bronze badges
Comments
lang-js
{ "key": []}this is the way to add an array into an objectaddModel.MyArray.push( { "SomeValue" : 1, "AnotherValue": a })afteraddModelis declared