Skip to content Skip to sidebar Skip to footer

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. Here's my models: public class Model1 {

Solution 1:

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:

functionModel2(jsonData ) {
        this.name       = jsonData.name;
        this.discovered = jsonData.discovered;
    };

    var objModel2_1= newModel2(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.

Post a Comment for "Add Items To Json Objects"