-3

I am sending C# List<string> to AJAX JSON method. But How can I iterate that JSON array?

[WebMethod]
    public static List<string> GetPreviousSaltsAndHashes(string name)
    {
        List<string> prevSalts = new List<string>();
       ....
       ....              
            conn.Open();
            SqlDataReader reader = cmd.ExecuteReader();



            if (reader.HasRows)
            {
                while (reader.Read())
                {                      
                    prevSalts.Add(reader.GetString(0));
                }

            }

            conn.Close();            


        return prevSalts;
    }


 $.ajax({
            type: 'POST',
            contentType: "application/json; charset=utf-8",
            url: 'NewPassword.aspx/GetPreviousSaltsAndHashes',
            data: "{'name':'" + username + "'}",
            dataType: "json",
            success: function (data) {
                PreviousSalts = data.d;
                alert(PreviousSalts);
            },
            error: function (xhr, status, error) {
                var exception = JSON.parse(xhr.responseText);                  
                alert(exception.Message);
            }
        });

//below part is not working. What is the way to iterate?
 $.each(PreviousSalts, function (index, PreviousSalt) {
                console.log(PreviousSalt);
                pass = $('#txtNewPass1').val();
                var combo = pass + PreviousSalt;
                var hash = new String(CryptoJS.SHA3(combo, { outputLength: 512 }));

                if (hash == newhash) {
                    alert("matched");
                    return false;
                }
            });
mason
  • 31,774
  • 10
  • 77
  • 121
James123
  • 11,184
  • 66
  • 189
  • 343
  • 2
    Describe "not working". Are you getting an error message? What does `console.log(PreviousSalt);` say, and what are you expected it to say? What does the received JSON look like? You need to be more specific in your question so we can help you! – mason Sep 23 '14 at 20:01
  • You must do all of your work in the ajax callback. When execution reaches the `$.each` call, `PreviousSalts` has not yet been populated by the result of the AJAX request. See [this question](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) for more information. – Andrew Whitaker Sep 23 '14 at 20:08

2 Answers2

1

You should switch to Web API if possible. ASMX is being phased out and has poor JSON support. I've been able to force ASMX to return JSON like this:

[WebMethod]
public static void GetPreviousSaltsAndHashes(string name)
{
    List<string> prevSalts= //blah blah, retrieve data
    HttpContext.Current.Response.ContentType="application/json";
    HttpContext.Current.Response.Write(JsonConvert.SerializeObject(prevSalts));
}

Obviously, you lose content negotiation and you're using outdated technology. You should switch to Web API. In fact, the code would largely be the same as what you posted. You just need to fix the routes.

Your JavaScript never reaches the $.each line with any data. That's because jQuery AJAX is asynchronous by default. It'll call the success function after it's received the response. So place that code in a function and tell jQuery's success handler what function to call.

$.ajax({
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        url: 'NewPassword.aspx/GetPreviousSaltsAndHashes',
        data: "{'name':'" + username + "'}",
        dataType: "json",
        success: function (data) {
            PreviousSalts = data.d;               
            alert(PreviousSalts);
            HandleResponse(PreviousSalts);
        },
        error: function (xhr, status, error) {
            var exception = JSON.parse(xhr.responseText);                  
            alert(exception.Message);
        }
    });

 function HandleResponse(PreviousSalts){
 $.each(PreviousSalts, function (index, PreviousSalt) {
            console.log(PreviousSalt);
            pass = $('#txtNewPass1').val();
            var combo = pass + PreviousSalt;
            var hash = new String(CryptoJS.SHA3(combo, { outputLength: 512 }));

            if (hash == newhash) {
                alert("matched");
                return false;
            }
        });
}
mason
  • 31,774
  • 10
  • 77
  • 121
0

First, you'll need to serialize your list into JSON. JSON is simply a JavaScript string representation of your data. .NET provides easy functions to make this happen. Here's a post with great info:

Serializing a list to JSON

Second, unless the .each code snippet is properly embedded into a callback already, you need to call that code from the success method of your AJAX request.

Community
  • 1
  • 1
Evan
  • 2,441
  • 23
  • 36