Ben Ben - 1 year ago 100
C# Question

Autocomplete with source read from JSON Array stored in Label not working

I am using JQuery Autocomplete, and want to populate it from a JSON Array read from a hidden Label.

This code:

string[] tags = { "Apple", "Orange", "Banana", "Lychee", "Pear", "Lemon" };
var json = JsonConvert.SerializeObject(tags);
lblJson.Text = json;

produces this result:

enter image description here

I am trying to then populate the autocomplete source with this array like this:

var availableTags = $("#lblJson").text();

but my autocomplete doesn't, err, autocomplete.

However, if I copy the JSON array directly into the Javascript code it works fine:

var availableTags = ["Apple", "Orange", "Banana", "Lychee", "Pear", "Lemon"];

Answer Source
var availableTags = $("#lblJson").text();

The availableTags you got here is not an array, but rather a string that contains a json array.

Since you are using jQuery, you can use this to parse it:

var json = $("#lblJson").text();
var availableTags = $.parseJSON(json);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download