Knockout JS:从 viewmodel 可观察数组创建 Json [英] Knockout JS: Creating Json from viewmodel observable array

查看:34
本文介绍了Knockout JS:从 viewmodel 可观察数组创建 Json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 html 表格,它的列是动态创建的.有添加行按钮向表格添加行和删除行按钮删除行.最后有一个保存按钮,我想从输入的表中获取所有数据并将其以 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.

表格设置一切正常.我遇到的唯一问题是从 observable 数组创建 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆