Fill javascript array with C# in ASP.NET.

This is a very simple code snippet in ASP.NET. In this article, I will show you how to fill JavaScript Array from C# code behind and then read the value of the Array on the client-side and display it to the page. ASP.NET WebForm provides A API, RegisterArrayDeclarationThat takes the value from C# and add it to the page as a JavaScript array.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ClientSideCalcGridview.aspx.cs"
   Inherits="ClientSideCalcGridview" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<html xmlns="">
<head runat="server">
   <title>Untitled Page</title>
   <form id="form1" runat="server">
           <input type="text" id="indexText" />
           <input type="button" id="showButton"
 value="Show Array Element By Index"
onclick="ShowItem(document.getElementById('indexText').value);" />

<script type="text/javascript">
       function ShowItem(index)
          alert('myArray['+index+'] = ' + myArray[index]);


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class ClientSideCalcGridview : System.Web.UI.Page
   protected void Page_Load(object sender, EventArgs e)
       DataSet ds = new DataSet();
       if (Session["dt"] == null)
           ds = c();
           ds = Session["dt"] as DataSet;
       foreach (DataRow dr in ds.Tables[0].Rows)
           this.ClientScript.RegisterArrayDeclaration("myArray", "'" + dr["Address"].ToString() + "'");

   public DataSet c()
       DataSet ds = new DataSet();
       DataTable dt = new DataTable("Company");
       DataRow dr;
       dt.Columns.Add(new DataColumn("accountNo", typeof(Int32)));
       dt.Columns.Add(new DataColumn("CompanyName", typeof(string)));
       dt.Columns.Add(new DataColumn("Address", typeof(string)));
       for (int i = 0; i <= 10; i++)
           dr = dt.NewRow();
           dr[0] = i;
           dr[1] = "Company" + i + Environment.NewLine + "Title" + i;
           dr[2] = "Address" + i.ToString();
       Session["dt"] = dt;
       return ds;
Next Post Previous Post
No Comment
Add Comment
comment url