Knockout JS:从viewmodel可观察数组创建Json [英] Knockout JS: Creating Json from viewmodel observable array
问题描述
我有一个html表,其列是动态创建的。添加行按钮可以向表中添加行,并删除行按钮以删除行。
最后有一个Save按钮,我想从输入的表中获取所有数据,并以json格式发送给我的mvc控制器。
I have a html table whose columns are dynamically created. There is add row button which adds row to the table and remove row button to remove the row. Finally there is a Save button where I want to get all the data from the table that was entered and send it in json format to my mvc controller.
表设置一切正常。我唯一的问题是从可观察数组创建json。
以下是我的小提琴:
The table setup all works fine. The only issue I am having is creating json from the observable array. Below is my fiddle:
https ://jsfiddle.net/4djn2zee/1/
如果单击添加一行或多行并输入两行数据。如果按下保存按钮,则有一个可观察的:
If you click add one or more rows and enter data to both the rows. If you press save button there is an observable as:
self.valuesData()
现在,如果你在控制台中看到这个值的价值如下:
Now the value of this if you see in console comes out to be as:
(2) [ValuesData, ValuesData]
进一步扩展:
(2) [ValuesData, ValuesData]
0:ValuesData {ID: "1", Co1: "2", Col2: "3", Col3: "4", Col4: "5", …}
1:ValuesData {ID: ƒ, Co1: ƒ, Col2: ƒ, Col3: ƒ, Col4: ƒ, …}
length:2
__proto__:Array(0)
因为我添加了2行我可以看到2的数组。
Since I added 2 rows I can see an array of 2.
现在,如果你看到上面我可以在第一行id,col1,col2等中看到我的数据。
我遇到的问题是如何从observable获取数据并构造我的json。
Now if you see above I can see my data in the first row id, col1, col2 etc. What I am having issue is how to get the data from the observable and construct my json.
我期待我的json如下所示:
I am expecting my json to be like as below:
{
"ID": "1",
"Co1": "2",
"Col2": "3",
"Col3": "4",
"Col4": "5",
"Col5": "6",
"Comment": "7"
},
{
"ID": "8",
"Co1": "9",
"Col2": "10",
"Col3": "11",
"Col4": "12",
"Col5": "13",
"Comment": "14"
}
更新:
我试过如下:
var dataToSave = $.map(self.valuesData(), function(item) {
var jsonToSend = {};
return jsonToSend;
});
再次如第一行所述,我可以看到数据,但不知道如何从中获取数据第二行和后续行。
Again as mentioned for the first row I can see the data but not sure how to get the data from the second and subsequent rows.
这是我更新的小提琴:
https://jsfiddle.net/4djn2zee/3/
推荐答案
试试这个:
var dataToSave = ko.toJSON(self.valuesData);
这篇关于Knockout JS:从viewmodel可观察数组创建Json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!