Pages

Free Hosting
Showing posts with label HTML. Show all posts
Showing posts with label HTML. Show all posts

Monday, October 17, 2011

Passing Array from server to client


This is a frequent requirement for an ASP.NET developer to pass a server side array to client side and access them through JavaScript. 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, the first one is how to pass the array from server side to client side and the second one is 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 by using “RegisterArrayDeclaration”.RegisterArrayDeclaration method registers a JavaScript array with the System.Web.UI.Page object. As the array object is registered with the “Page" object, we can access it from JavaScript easily.RegisterArrayDeclaration takes array name and value of the array element as arguments.

In the below example, I have registered one array with the 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 does the above declaration do? This is nothing but a declaration of a JavaScript array like:



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

This “Skills” array is now only a JavaScript array which is easily accessible by client side code. Now let’s take a look at how to access them and how to bind them in a dropdown list. 
In my form, I have an HTML
 select element and one HTML Button. I want my server side (which is now a client side) array to bind in the dropdown list.


  <select id="ddlNames" name="D1">
    </select><input id="BtnNameLoad" type="button"
         value="Load Name" onclick="return BtnNameLoad_onclick()" />


Below is the code snippet for binding the array to HTML control:



function BtnNameLoad_onclick() {

            //Get The Control ID for the dropdown
            var listID = document.getElementById("ddlNames");
            //Check if the object is not null
            if (listID != null) {
                for (var i = 0; i < Skills.length; i++) {
                   // Create and Element Object of type "option"
                    var opt = document.createElement("option");
                    //Add the option element to the select item
                    listID.options.add(opt);
                    //Reading Element From Array
                    opt.text = Skills[i];
                }
            }
        }