Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically create javascript array with c# code behind

I am updating an old classic ASP site to a new .net 3.5 version. The page has a custom list control which the client (my boss) wants to keep. This list control requires several arrays in order to work correctly. the array is a multi-dimensional list of publications. This is what it looks like:

var publicationTable = [
    [31422,"Abilene Reporter News","Abilene","TX",false,"D",0],
    [313844,"Acadiana Weekly","Opelousas","LA",false,"W",1],
    [527825,"Action Advertiser","Fond du Lac","WI",false,"W",2]...n]

I want to generate this array server side and register it. I have looked at the msdn but this is a little trivial. The conceptual issue is that the array is a mixture of string and ints and I am not sure how to recreate this, so how?

like image 763
flavour404 Avatar asked May 07 '11 00:05

flavour404


2 Answers

You should do this:

Code behind:

using System.Web.Script.Serialization;
...
public string getJson(){
   var publicationTable = new List<object>{
      new []{ 31422,"Abilene Reporter News","Abilene","TX",false,"D",0},
      new []{ 313844,"Acadiana Weekly","Opelousas","LA",false,"W",1 },
      new []{ 527825,"Action Advertiser","Fond du Lac","WI",false,"W",2}
   };
   return (new JavaScriptSerializer()).Serialize(publicationTable);
}

Ase you see, to create an array of mixed types, we create an array of anonymous type with new []. You could also have done it with new object[].

Aspx file:

<script>
    var publicationTable = <%= getJson() %>;
</script>

Hope this helps. Cheers

like image 188
Edgar Villegas Alvarado Avatar answered Oct 12 '22 06:10

Edgar Villegas Alvarado


I think a List<List<object>> containing your items, passed through the JavaScriptSerializer would do the trick. Given that this data probably comes from a more structured data type, you could probably do better than List<List<object>>, but the JavaScriptSerializer is probably what you're after.

like image 26
spender Avatar answered Oct 12 '22 05:10

spender