So, recently I’ve been looking into the HTML5 Indexeddb feature which is controlled with Javascript, and how to incorporate this with an SQL Server database to share and copy information across so that a version of the database is available offline.
The conundrum that I have is finding the best way to pass a set of objects from an SQL Server database through to the javascript of a browser, using C# to get the values from the database.
Though there are many little “hacks” that can be done (e.g Putting data into labels and then having the Javascript just pick it up document.getElementById(“DataHere”).value;) I was wondering if there were more efficient ways of passing the contents of a database across?
At the moment I have a method that generates an array of strings (all in the JSON format, using the JSON.Net package) as an example of what would be returned from the database.
public string[] GenerateEmployeeSample() {
List<Employee> listEmps = new List<Employee>();
string[] listJSON = new string[64];
string[] FirstNames = {"Alonso", "Alfred", "Angus", "Alfresco" };
string[] LastNames = {"Johnson","Williams", "Zelwegger", "Jones" };
string[] Departments = {"Finance", "Cleaning", "Pusher", "Stairs" };
string emailEnd = "@email.com";
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
for (int k = 0; k < 4; k++) {
Employee tempEmp = new Employee();
tempEmp.FirstName = FirstNames[i];
tempEmp.LastName = LastNames[j];
tempEmp.Department = Departments[k];
tempEmp.Email = FirstNames[i] + "." + LastNames[j] + emailEnd;
listEmps.Add(tempEmp);
}
}
}
int count = 0;
foreach(Employee emp in listEmps){
string tempString = JsonConvert.SerializeObject(emp);
listJSON[count] = tempString;
count++;
}
return listJSON;
}
So now I have a set of data, how would I be able to pass this array through to Javascript?
I apologise if this is a trivial question but Javascript is still rather new to me, and after reading through quite a few examples that either didn’t do what I wanted or just outright didn’t work I am at a bit of a loss.
Thanks very much for reading!
To be more specific, you would make a resource (be it an aspx page or or a json file etc) that returns a JSON string when requested. You’re already partway there with this step, because you’ve already got the code for serializing objects as JSON. A simple way of doing this would be to have a page that outputs the return value of this function using
Response.Write(GenerateEmployeeSample());Then you would use the XMLHttpRequest object to request this resource, and parse the returned JSON using javascript’s
JSON.parse, which returns a native javascript object. You may then do with this object as you please.