65.9K
CodeProject is changing. Read more.
Home

Pass an array from ASP.NET(server) to javascript (client side)

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.44/5 (7 votes)

Jul 5, 2010

CPOL
viewsIcon

25736

I see many blogs asking a way to pass an array from server side to java script, most of them are unanswered or suggesting a ListBox (which is not simple). But to pass an array from server side to access it from client side we can use RegisterArrayDeclaration method. Here is a simple example In your code behind you can use the method like,
protected void Page_Load(object sender, EventArgs e)
{
    RegisterArrayDeclaration("MyArray", "'Welcome'");
    RegisterArrayDeclaration("MyArray", "'Hai'");
    RegisterArrayDeclaration("MyArray", "'Hello'");
    RegisterArrayDeclaration("MyArray", "'Best'");
    RegisterArrayDeclaration("MyArray", "'Super'");
}
You can access this array from client side Javascript code,
for (var i = 0; i < MyArray.length; i++) {
       alert(MyArray[i]);
}