Monday, December 3, 2012

Bind DropDownList from javascript

Generally DropDownList also we can bind from clientside. The step by step procedure i have mentioned here.

 we have to get the data from the database and need to bind to dropdown means we need to get it on "ListView" is the better way. I have used PageMethods to get the data to clientside.

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>

Here the pageLoad method works just like server side pageload event. In this pageload i have got data and binded to dropdownlist. In CallMethod function "result" indicates the obtained data which we need to bind to dropdown in the form of list.

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;
    }

By this pageMethod list<string> is returning to javascript function.

You can get the sample code by the attached document.....

No comments:

Post a Comment