0

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?

2
  • i guess i do not understand you correctly...{ "key": []} this is the way to add an array into an object Commented Aug 18, 2016 at 12:47
  • You can also push into the array with addModel.MyArray.push( { "SomeValue" : 1, "AnotherValue": a }) after addModel is declared Commented Aug 18, 2016 at 12:52

4 Answers 4

2

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 }
    ]
}
Sign up to request clarification or add additional context in comments.

Comments

1
"MyArray": [
 {
    "SomeValue": 1,
    "AnotherValue": a
 },
 {
    "SomeValue": 1,
    "AnotherValue": a
}
]

Comments

0

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

Comments

0
var myArray = [
    {
        "a":1,
        "b":2
    },
    {
        "a":1,
        "b":2
    }
];

var addModel = {
    "SomeValue": {
        "Some": "example",
        "Value": "example"
    },
    "AnotherValue": "example",
    "myArray": myArray
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.