Home > database >  How to pass multiple objects with Json Stringify?
How to pass multiple objects with Json Stringify?

Time:08-16

How do I pass multiple objects with Json Stringify? string[] activities is populated and if I temporarily remove it, then playerLevels becomes populated.

I'm still new to javascript so not really sure what to attempt

Below is my code

        let collection = document.getElementsByClassName("skill-icon-selected");
        const skillsChosen = new Array;
        for (var i = 0; i < collection.length; i  )
        {
            var split = collection[i].id.split("-");
            skillsChosen.push(split[0]);
        }

        let levelCollection = document.getElementsByClassName("skill-input");
        const playerLevels = new Array;        
        for (var i = 0; i < levelCollection.length; i  )
        {
    
            playerLevels.push(levelCollection[i].value);
            
        }

        $.ajax({
            url: "/index?handler=GetActivity",
            type: "POST",
            contentType: 'application/json',
            dataType: "json",
            data: JSON.stringify(skillsChosen, playerLevels),
             headers: {
                RequestVerificationToken:
                    $('input:hidden[name="__RequestVerificationToken"]').val()
            },
            success: function(result)
            {
                console.log(result);
            },
            error: function(e)
            {
                console.log(e);
            },

            contentType: "application/json"
        });

cshtml.cs

  public IActionResult OnPostGetActivity([FromBody] string[] activities, [FromBody] int[] playerLevels)
        {
            allActivities = _context.Activities.ToList();

            if (activities.Length > 0)
            {
                System.Diagnostics.Debug.WriteLine("testing "   activities[0]);
            }
            foreach (Activity activity in allActivities)
            {
                if (activities.Contains(activity.Skill.ToLower()))
                {
                    //if user skill is between min and max

                    System.Diagnostics.Debug.Write(activity.ActivityName);
                }
            }
            return new JsonResult("testing");
        }

CodePudding user response:

The second parameter of JSON.stringify is not supposed to be a second value (the documentation)

If you want to serialize both variables at the same time, you can put them in an object like this

JSON.stringify([{skillsChosen, playerLevels}),

CodePudding user response:

I think you'd better to create a model which contains string[] and int[]:

var model={"activities":skillsChosen,"playerLevels":playerLevels};
 $.ajax({
            url: "/index?handler=GetActivity",
            type: "POST",
            contentType: 'application/json',
            dataType: "json",
            data: JSON.stringify(model),
             headers: {
                RequestVerificationToken:
                    $('input:hidden[name="__RequestVerificationToken"]').val()
            },
            success: function(result)
            {
                console.log(result);
            },
            error: function(e)
            {
                console.log(e);
            },

            contentType: "application/json"
        });

Model:

public class TestModel{
 public string[] activities{get;set;}
 public int[] playerLevels{get;set;}
}

cshtml.cs:

public IActionResult OnPostGetActivity([FromBody]TestModel testModel)
        {
            allActivities = _context.Activities.ToList();

            if (activities.Length > 0)
            {
                System.Diagnostics.Debug.WriteLine("testing "   activities[0]);
            }
            foreach (Activity activity in allActivities)
            {
                if (activities.Contains(activity.Skill.ToLower()))
                {
                    //if user skill is between min and max

                    System.Diagnostics.Debug.Write(activity.ActivityName);
                }
            }
            return new JsonResult("testing");
        }
  • Related