简体   繁体   English

将项目添加到JSON对象

[英]Add items to JSON objects

I have a situation that I just cannot figure out how to do. 我有一种情况,我无法弄清楚该怎么做。 I'm trying to add items to a JSON object that was sent from the controller. 我正在尝试将项目添加到从控制器发送的JSON对象中。

Here's my models: 这是我的模型:

 public class Model1
 {
     public Model2 item {get;set;}
     public List<Model2> items {get;set;}
      //

And in the page 并在页面中

 var jsonData = @Html.Raw(JSON.Encode(Model))

This gives me the basic but empty model. 这给了我基本但空洞的模型。 Now in the page I fill in various fields and want to add the items into the model for posting. 现在,在页面中,我填写了各个字段,并希望将项目添加到模型中以进行发布。 So: 所以:

 jsonData.item.field1 = $("#field1").val();

Then I want to add to the list of items, but I cannot find anything that works: 然后,我想添加到项目列表中,但是找不到任何有效的方法:

 jsonData.items.add(jsonData.item)

doesn't work throws an error. 不起作用会引发错误。

 jsonData.items.push(jsonData.item);  

works but every item I add ends up the same. 可以,但是我添加的每个项目都一样。 Meaning that when I add the second item there are two in the list but they have the same values. 这意味着当我添加第二个项目时,列表中有两个,但是它们具有相同的值。 Any help would be appreciated. 任何帮助,将不胜感激。

As we know, Javascript can be used as OO language and classes and objects can be created on the fly in javascript. 众所周知,JavaScript可以用作OO语言,并且可以使用javascript快速创建类和对象。 Per my understanding, you are using below code to get class attributes in the JavaScript 据我了解,您正在使用以下代码在JavaScript中获取类属性

 var jsonData = @Html.Raw(JSON.Encode(Model))

When this JSON is returned to the client side, it is considered as single object. 当此JSON返回客户端时,它将被视为单个对象。

So, you can declare a function, acting as class: 因此,您可以声明一个充当类的函数:

   function Model2(jsonData ) {
        this.name       = jsonData.name;
        this.discovered = jsonData.discovered;
    };

    var objModel2_1= new Model2(jsonData);

Now, you can declare an array to add the objModel2. 现在,您可以声明一个数组以添加objModel2。

var arrModel2=[];
// add new objects

attModel.push(objModel2_1);   

Finally, when you are done, you can use existing jsonData object to fill ie 最后,完成后,您可以使用现有的jsonData对象来填充

   jsonData.item=objModel2_1;
   jsonData.items=attModel;

Hope, this will help you. 希望这个能对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM