Wednesday 5 September 2012

Bind DropdownList without postback using javascript

 

Generally dropdownlist is the most useful control in our applications but in some cases it is difficult to get flexible binding. This type of binding done by javascript is more efficient and easy to handle.

This type of binding can get data from PageMethods (or) WebServices etc. By getting the data we can bind to dropdownlist through javascript.

JAVASCRIPT:

<script type="text/javascript">

        function pageLoad() {
            PageMethods.GetData(CallMethod);
        }

        function CallMethod(result) {
            var ddl = document.getElementById("ddl");
            for (D = 0; D < result.length; D++) {
                opt = new Option(result[D], result[D]);
                ddl.add(opt);
            }
        }

</script>

pageLoad function is just similar to PageLoad event is server side. In clientside pageLoad i am calling PageMethods and getting the data here. The obtained data is in the form of "List" and can be easily handled.

PAGEMETHODS:
[WebMethod(EnableSession=true)]
    public static List<string> GetData()
    {
        List<string> list = new List<string>();
        list.Add("one");
        list.Add("two");
        list.Add("three");
        list.Add("four");
        list.Add("five");
        return list;
    }

Here in this case i have done a sample list<string>. The final List will get returned to the javascript function.

Sample code will be obtained here Click Here