How to pass ASP.NET server side array to client side and binding them with Html element?

This is a very often requirement for an ASP.NET Developer to pass a sever side array to client side and access them through java Script. There are several ways to do that. But here I am describing one of the simplest steps to pass server side array to client side. In this blog post you will get to know two things, first one is the how to pass the array from server side to client side and second one is the how to bind that array to an empty “html dropdown” list.

Well, the easiest way to pass the server side array to a client side is  using  “RegisterArrayDeclaration” . RegisterArrayDeclaration method registers a javascript array with the System.Web.UI.Page Object. As the array object registered with the “Page” object so we can access it from javascript easily. RegisterArrayDeclaration takes array name and value of the array element as argument.

In below example, I have registered one array with name of “Skills”.

  protected void Page_Load(object sender, EventArgs e)
    {
       // Register List of Languages
        Page.ClientScript.RegisterArrayDeclaration("Skills", "'C#'");
        Page.ClientScript.RegisterArrayDeclaration("Skills", "'VB.NET'");
        Page.ClientScript.RegisterArrayDeclaration("Skills", "'C'");
        Page.ClientScript.RegisterArrayDeclaration("Skills", "'C++'");
    }

Now, what above declaration does?  This is nothing but a declaration of a java script array like,

Var Skills = new Array('C#', 'VB.NET','C','C++');

These “Skills” array is now only a JavaScript array which is easily accessible by client side code. Now Let’s have a look how to access them and how to bind them in a dropdown list.