I have the following JQUERY code that I’m expecting to return 3 json results to the console. What’s happening is I’m getting 3 copies of the results of the first return.
so for example I’m trying to see filename’s, and I’m getting back “first name, first name, first name” instead of “first name, second name, third name”
here’s my code:
$.ajax({
type: "POST",
url: "front.aspx/GetData",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var obj = msg.d;
$.each(obj, function(index, value){
console.log(value);
});
}
});
what am I doing wrong with the each function?
I don’t think you need my CS code to tell me what I’m doing wrong, but incase you do, here it is:
public class LoadData {
public string filename;
public string date;
public string filetype;
public Int32 height;
public Int32 width;
public string uploadGroup;
public string title;
public string uniqueID;
public string uploader;
public string uniqueIDnoExt;
}
[WebMethod]
public static List<LoadData> GetData() {
LoadData b = new LoadData();
List<LoadData> info = new List<LoadData>();
SqlDataReader reader;
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
SqlCommand command = new SqlCommand("SELECT * FROM uploads ORDER BY id DESC", connection);
command.Parameters.Add(new SqlParameter("uploader", "anonymous"));
reader = command.ExecuteReader();
while (reader.Read()) {
b.filename = reader.GetString(1);
b.date = reader.GetSqlDateTime(3).ToString();
b.filetype = reader.GetString(4);
b.height = (Int32)reader.GetSqlInt32(5);
b.width = (Int32)reader.GetSqlInt32(6);
b.uploadGroup = reader.GetString(7);
b.title = reader.GetString(8);
b.uniqueID = reader.GetString(9);
b.uploader = reader.GetString(10);
b.uniqueIDnoExt = reader.GetString(12);
info.Add(b);
}
return info;
}
Move this line
inside the loop.
The way you have it now you make only one line of data. The
List<>holds the reference, it does not recreate them. So if you’re not making new data, you’re not inserting any new data (as it is now). You’re just adding first one in memory, and then changing the values.Also you can read :
http://en.wikipedia.org/wiki/Linked_list
By the way.
You have left open many things, you will soon end up without resources. Use the
usingkeyword on the objects that need to be closed. And, for speed, use a static string (to read only) on the connection string.