Injecting an Array into Javascript from Code Behind by David Ballantyne
The Problem:

I needed an array in my javascript that looked like this:
var arrAverageSalary =[39, 7,21,49, 6,13, 3,12, 1,33,24,18,46,14,37,38,36,44,42,34, 5, 2,20,15,51,32,47,40,27,16, 8,31, 4,30,35,26,43,17,19,11,45,50,41,23,29,22,10, 9,48,28,25];

Hard-coded works easy enough, but the values were stored in the database. The values take some processing power so they were pre-processed and stored in a database field as a string:
39, 7,21,49, 6,13, 3,12, 1,33,24,18,46,14,37,38,36,44,42,34, 5, 2,20,15,51,32,47,40,27,16, 8,31, 4,30,35,26,43,17,19,11,45,50,41,23,29,22,10, 9,48,28,25

The Solution:

Add this to inject the array:
Page.ClientScript.RegisterArrayDeclaration("ArrayName", "ArrayValues");

Where
  • ArrayName is the array name used in the Javascript.
  • ArrayValues is the string representation of the array.
In my case, it looked like this:
Page.ClientScript.RegisterArrayDeclaration("arrAverageSalary", dr["AvereageSalaryRank"].ToString());

This would also have worked:
Page.ClientScript.RegisterArrayDeclaration("arrAverageSalary", "39, 7,21,49, 6,13, 3,12, 1,33,24,18,46,14,37,38,36,44,42,34, 5, 2,20,15,51,32,47,40,27,16, 8,31, 4,30,35,26,43,17,19,11,45,50,41,23,29,22,10, 9,48,28,25");

What Did Not Work:
  • <asp:Literal> - Wouldn't render arrays.
  • <asp:HiddenField> and Javascript Trickery - Caused the client to crash.
  • JSON.Parse - A little more complicated than I wanted because I already had the arrays as a string.
  • Cursing - Did make me feel a bit better.