将项目添加到JSON对象 [英] Add items to JSON objects

查看:131
本文介绍了将项目添加到JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有,我只是想不出怎么办的情况。我试图将项目添加到从控制器发送一个JSON对象。

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.

下面是我的模型:

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

和页面

 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);  

作品但我每次添加项目结束一样。这意味着,当我添加第二个项目中有两个列表中,但它们具有相同的价值观。任何帮助将是AP preciated。

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.

推荐答案

我们知道,使用Javascript可以作为面向对象的语言和类和对象可在JavaScript动态创建。
按我的理解,您使用的是低于code来获得在JavaScript类的属性。

As we know, Javascript can be used as OO language and classes and objects can be created on the fly in javascript. Per my understanding, you are using below code to get class attributes in the JavaScript

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

当此JSON被返回到客户端,它被认为是<强>单个对象。

When this JSON is returned to the client side, it is considered as single object.

所以,你可以声明一个函数,作为类:

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);

现在,
你可以声明一个数组添加objModel2。

Now, you can declare an array to add the objModel2.

var arrModel2=[];
// add new objects

attModel.push(objModel2_1);   

最后,
 当您完成时,您可以使用现有jsonData对象填写
即。

Finally, when you are done, you can use existing jsonData object to fill i.e.

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

希望,这将帮助你。

Hope, this will help you.

这篇关于将项目添加到JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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