Monday, 24 November 2014

Reloading a DropDownList using jQuery

Note: This solution will not be applicable for ASP.Net with ViewState (as ViewState will not be updated while using Webmethod call to reload the control).

<asp:DropDownList ID="ddlTemplate" runat="server" ClientIDMode="Static" ></asp:DropDownList>

I kept the control clientIDmode static, it is necessary when we use Master page and the javascript code is in separate file. With HTML combo box control we can remove some of the code specific that is used to handle asp.net control.

The frontend javascript/jquery code :

function GetTemplates() {
    var ddlTestDropDownListXML = '#ddlTemplate';
    var tableName = "TempDataTable";
    $.ajax({
        type: "POST",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        url: "Search.aspx/GetTemplates",
        data: '{tableName: "' + tableName + '"}',
        success: function (response) {            
            $(ddlTestDropDownListXML).empty().append($("<option></option>").val("[-]").html("Select"));
            $.each(response.d, function () {
                $(ddlTestDropDownListXML).append($("<option></option>").val(this['Value']).html(this['Text']));
            });
        },
        error: function (xhr, status, error) {
            var err = eval("(" + xhr.responseText + ")");
            alert(err.Message);
        }
    });
}


And the code behind looks like below:

        [System.Web.Services.WebMethod]
        public static ArrayList GetTemplates(string tableName)
        {
            AdBusiness ab = new AdBusiness();
            DataTable templateTable = new DataTable();
            ArrayList lstArrTemplate = new ArrayList();            
            try
            {
                templateTable = ab.GetTemplates();
                foreach (DataRow row in templateTable.Rows)
                {
                    lstArrTemplate.Add(new ListItem((string)row[0], (string)row[1]));
                }
                return lstArrTemplate;
            }
            catch (Exception ex)
            {
                return lstArrTemplate;
            }
        }

       

No comments: