0

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");
        }
Yiyi You
  • 16,875
  • 1
  • 10
  • 22
D74
  • 41
  • 5
  • I think your data object should be `{ activities: skillsChosen, playerLevels }`, also not sure why you need to stringify it – Pete Aug 11 '22 at 12:49
  • Hi @Pete I gave that a go (with and without the stringify) and activities is appearing as null in the cshtml.cs while debugging – D74 Aug 11 '22 at 13:33
  • Have you tried removing the `[FromBody]` – Pete Aug 11 '22 at 13:46
  • @Pete string[] activities then becomes empty (not null), not sure if that helps – D74 Aug 11 '22 at 14:59

2 Answers2

0

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}),
Krayorn
  • 95
  • 8
  • Hi, I should have put in the original post, I attempted that but it passes null through to my method, I'm not sure if i need to handle it different in my cshtml.cs – D74 Aug 11 '22 at 13:04
  • Alright, then i think Pete suggestion on your question may do the trick: `{ activities: skillsChosen, playerLevels }` should allow you to access the content of the `skillsChosen` variable under the name `activities`. I'm not very familiar with how you get the data in the rest of your code, but if you have any issue it shouldn't be on the javascript side – Krayorn Aug 11 '22 at 13:24
  • Hmm I've tried that after Pete suggested it and activities in the .cshtml.cs is still null, I imagine something is wrong on the C# side then – D74 Aug 11 '22 at 13:32
  • Ok, so i checked [this question](https://stackoverflow.com/questions/40853188/frombody-string-parameter-is-giving-null) and maybe there is somebody you could use there. Maybe try to create a Class with `[]string activities` and `[]int playerlevels` and just use `[FromBody] NameOfYourModelClass variableName` – Krayorn Aug 11 '22 at 13:44
  • Hmm I've just tried that, the variable is null, do you have any idea how I would format my data in the ajax request? – D74 Aug 11 '22 at 15:09
  • @D74 You should also be able to access your data from the request directly `HttpContext.Request.Body` in your cs file as mentionned [there](https://stackoverflow.com/a/40853424/19051393). But it seems to be a totally different question now, i suggest maybe you close this one and create a new one where some other users might be more knowledgable – Krayorn Aug 11 '22 at 20:43
0

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");
        }
Yiyi You
  • 16,875
  • 1
  • 10
  • 22