Thursday, January 10, 2013

How to pass ASP.NET server side array to client side

In ASP.Net , this is a very often requirement to pass the server side array to client side and access them using java script. It this post I am describing the simplest way to pass the server side array to client side. Here I will show you two things, one is how to pass the server side array to client side and bind that array to empty "htmldropdown" list.

The easiest way to pass the server side array to client side is using "RegisterArrayDeclaration". RegisterArrayDeclaration method registers the java script array with 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.

Lets see the example, In this example I have registered one array with the name "Countries".

protected void Page_Load(object sender, EventArgs e)
{
   //Register List of Countries
   Page.ClientScript.RegisterArrayDeclaration("Countries", "'India'");
   Page.ClientScript.RegisterArrayDeclaration("Countries", "'USA'");
   Page.ClientScript.RegisterArrayDeclaration("Countries", "'England'");
   Page.ClientScript.RegisterArrayDeclaration("Countries", "'Sri Lanka'");
}

The above code will declare a java script array like, 
 
var Countries = new Array('India','USA','England','Sri Lanka');

This "Countries" array is now only the java script array which can be easily accessible by client side code. Now, let’s have to look how to access the array and bind it to dropdown list. I have an HTML Select element and one HTML button .

<input id="btnLoadCountry" type="button" value="Load Country" onclick="return LoadCountry()" />
<select name="ddlCountry" id="ddlCountry"></select>
Below is the java script code block to access the array values and bind it to select element.

<script type="text/javascript">
    function LoadCountry() {        
        var ddlCountry = document.getElementById('ddlCountry');
        if (ddlCountry != null) {
            for (var i = 0; i < Countries.length; i++) {
                //Creating option element
                var oOption = document.createElement("option");
                oOption.text = Countries[i];
                if (navigator.appName == "Microsoft Internet Explorer") {
                    // since appendchild is not working in IE so we used add method
                    ddlCountry.add(oOption);
                }
                else {
                    ddlCountry.appendChild(oOption);
                }
            }
        }
        return false;
    }
</script>

Below is the sample output:
Happy coding!!
kick it on DotNetKicks.com

No comments:

Post a Comment

^ Scroll to Top