Wednesday, August 6, 2014

Create AJAX dropdownlist (select) using jQuery



Given below is an example of AJAX drop down list which fills data by making an AJAX call and also persists data on post back.

1) Create an AJAX handler

public class AjaxHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            if (HttpContext.Current.Request.QueryString["getDDLData"] == "1")
            {
                List<DDLData> values = new List<DDLData>();

                values.Add(new DDLData() { Text = "Option1", Value = "1" });
                values.Add(new DDLData() { Text = "Option2", Value = "2" });
                values.Add(new DDLData() { Text = "Option3", Value = "3" });

                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string result = serializer.Serialize(values);

                context.Response.ContentType = "text/json";
                context.Response.Write(result.ToString());
            }
           
        }
        public class DDLData { public string Text; public string Value; }
        public bool IsReusable
        {
            get { return true; }
        }
    }

Make sure that you declare AJAX handler information in web.config. To learn about AJAX call check the AJAX call related articles this blog
  <system.webServer>
     <modules runAllManagedModulesForAllRequests="true"/>
    <handlers>
      <add name="ajaxHandler" verb="GET,POST" path="RequestHandler.aspx" type="AJAXAsptest.AjaxHandler" />
    </handlers>
  </system.webServer>

 2) Create a “Select” element in HTML

    <select name="ddlData" id="ddlData">
            <option></option>
</select> 

 3) Make AJAX call to the handler and fill the dropdown list

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
    <script>
        var selectedValue = '<%= Request.Form["ddlData"]!=null?Request.Form["ddlData"]:""%>';
        $.ajax({ url: "RequestHandler.aspx?getDDLData=1",
            success: function (data) {//Get result object from server
                var elementRef = $("#ddlData");
                elementRef.append(new Option("Select", "Select", false, true));
                $.each(data, function () {
                    elementRef.append(new Option(this.Text, this.Value));
                });
                if (selectedValue != '') {
                    elementRef.val(selectedValue);
                }
            }
        });
    </script>

 4) On server side you can get the selected value of dropdown from the “form” data

Response.Write(Request.Form["ddlData"]);