Saturday, 21 June 2014

Data Load into DropDownList using JQuery

Normally, We have doing data load into DropDownList using server side code C# in Asp.net.But, step to improve performance on data load using jQuery.


Bellow jQuery code using in aspx page 

 $(document).ready(function () {
            $.ajax({
                type: "POST",
                url: "Default.aspx/LoadDropDownValues",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    $.each(msg.d, function (index, item) {
                        $("#ddlRecords").get(0).options[$("#ddlRecords").get(0).options.length] = new Option(item.dropDownValue, item.dropDownIndex);
                    });
                },
                error: function () {
                    alert("Failed to load names"); 
                }
            });
        }); 

And With in Body

<form id="form1" runat="server">
    <div>
        <input id="btnLoadDropDown" type="button" value="Load DropDown"/>
        <asp:DropDownList runat="server" ID="ddlRecords" Width="125px" Height="25px">
        </asp:DropDownList>
    </div>
    </form>

Server side to fetch database table values or static values like.

[WebMethod]
    public static List<DropdownValues> LoadDropDownValues()
    {
        List<DropdownValues> lstDD = new List<DropdownValues>();
        string[] alpha = new string[5] { "ONE", "TWO", "THREE", "FOUR", "FIVE" };
        for (int i = 0; i < 5; i++)
        {
            DropdownValues dd = new DropdownValues();
            dd.dropDownIndex = i;
            dd.dropDownValue = alpha[i];
            lstDD.Add(dd);
        }
        return lstDD;
    }

We should use [WebMethod] above used method and this method should be in static.

public class DropdownValues
    {
        public int dropDownIndex;
        public string dropDownValue;
    }


Finally, data load into DropDownList on client side.We have to achieve step to improve performance.  

No comments:

Post a Comment