Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
170 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

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

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

var arrModel2=[];
// add new objects

attModel.push(objModel2_1);   

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...