2016-08-18 56 views
0

陣列我有一個ASP.NET的API,它需要一個字符串模式:的Javascript:內對象

[HttpPost] 
public ActionResult Add(string model) 
{ 

    var m = JsonConvert.DeserializeObject<CustomModel>(model); 

    ... 

} 

到目前爲止,我一直在做這將數據傳遞給它:

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

var model = JSON.stringify(addModel); 

而且它工作得很好。但現在我需要出貨數據是這樣的:

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, 
} 

如何添加的對象,因此它可以被傳遞到後端以正確的格式?

+0

我想我不明白你的意思......'{「key」:[]}'這是將數組添加到對象的方式 – messerbill

+0

您也可以將數組推入數組'addModel'聲明後addModel.MyArray.push({「SomeValue」:1,「AnotherValue」:a})' –

回答

0

數組你可以把它們直接與

addModel.MyArray[0] = { "SomeValue" : 1, "AnotherValue": a }; 

你可以推到陣列

addModel.MyArray.push({ "SomeValue" : 1, "AnotherValue": a }); 

addModel宣佈

+0

謝謝!這工作得很好 –

2

就宣佈它作爲像這樣

var addModel = { 
    "SomeValue": { 
     "Some": "example", 
     "Value": "example" 
    }, 
    "AnotherValue": "example",  
    "MyArray": [ 
     { "SomeValue" : 1, "AnotherValue": a }, 
     { "SomeValue" : 1, "AnotherValue": a } 
    ] 
} 
1
"MyArray": [ 
{ 
    "SomeValue": 1, 
    "AnotherValue": a 
}, 
{ 
    "SomeValue": 1, 
    "AnotherValue": a 
} 
] 
0
var myArray = [ 
    { 
     "a":1, 
     "b":2 
    }, 
    { 
     "a":1, 
     "b":2 
    } 
]; 

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