1

In my controller I have a method that gets triggered by an AJAX call. I have a list of strings that I want to return

List<string> Usernames = new List<string>();

Then when data is loaded into Usernames I convert it into JSON

var JsonResults = Json(Usernames);

finally I return that JSON as below

return Json(new { success = true, resultsList =JsonResults });

In JavaScript, How can I loop through that array resultsList? Here is what the JS code looks like -

$.ajax({
    url: "@Url.Action("StartNewChat")",
    data: { SearchedText: searchedText },
    type: "GET",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (result) {
        if (result.success == true) {

            // READ THROUGH result.resultsList                
        }
    }
});

I tried JSON.parse() and result.resultsList[0] and converting result.resultsList into string and back to JSON it didn't work.

Edit:
When I do a console.log(result.resultsList) here is what I get which is pretty strange

{"contentType":null,"serializerSettings":null,"statusCode":null,"value":["a","aa","aaa"]}

the last array is the result from Username array in c#

2
  • What version of .NET Core are you using? Commented Jan 25, 2021 at 2:06
  • its .Net Core 5 Commented Jan 25, 2021 at 2:14

4 Answers 4

2

I'm not familiar with the Json method you are using, but from version 3.1 .Net Core has its own json serializer JsonSerializer (in System.Text.Json namespace) and I'm going to use that one in my answer.

As of your issue, you are serializing twice and it might not give you the resultsList in your final result as an array of string which you might be expecting.

Your first conversion will result in an array of strings -

["alice","bob","charlie"]

But your second conversion, depending on the serializer used, might put the entire array above inside a string and give that as the value of resultsList in your final result.

You should serialize once, the final object only -

// you need to import the following
// using System.Text.Json;

List<string> userNames = new List<string>();
names.Add("alice");
names.Add("bob");
names.Add("charlie");

return JsonSerializer.Serialize(new { success = true, resultsList = userNames });

It will give you resultsList as an array of strings -

{"success":true,"resultsList":["alice","bob","charlie"]}

Then you can loop through that array on the client end like -

result.resultsList.forEach(p=> console.log(p))
Sign up to request clarification or add additional context in comments.

Comments

0

The response has already a JSON so no need to parse anything.

It will be something like this:

$.ajax({

              url: "@Url.Action("StartNewChat")",
              data: { SearchedText: searchedText},
              type: "GET",
              contentType: "application/json; charset=utf-8",
              dataType: "json",
              success: function (result) {
                if (result.success == true)
                {
                      
                    result.resultsList.forEach( el => {
                        console.log(el)
                    })
                      
                }
            }
        });
    });
    ```

2 Comments

didnt work JS error : result.resultsList.forEach is not a function
I think the reason is JSON() in C# actually returns some other stuff too as well?!
0

sometimes you have to parse the json response first try this. straight after the success line

let result = JSON.parse(result);

Then

if (result.success == true)
{                      
  result.resultsList.forEach( el => {
    console.log(el)
  })                      
}

Comments

0

You can try this using by through the resultlist length.

          $.ajax({
          url: "@Url.Action("StartNewChat")",
          data: { SearchedText: searchedText},
          type: "GET",
          contentType: "application/json; charset=utf-8",
          dataType: "json",
          success: function (result) {
            if (result.success == true)
            {
             for (var i = 0; i <result.resultsList.length; i++) {
                   console.log(result.resultsList[i]);
               }     
            }
        }
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.