Fill ASP.Net dropdownlist using jQuery from Java Script and Set selectedtext after jQuery populated dropdownlist



In my application I have requirement to fill drop down using Jquery AJAX. User will not get any postback and drop down bind
smoothly.

In my dropdown, ID and text are same. for different ID and text you have to modify code little bit.



$.ajax({
                    type: "POST",
                    url: "EntityObject.aspx/GetValues",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    data: "{'ID':'" + ID + "'}",
                    success: function (result) {

                        document.getElementById('<%= dropdown.ClientID %>').options.length = 0;

                        $.each(result.d, function (key, value) {
                            $('#<%=dropdown.ClientID%>').append($("<option></option>").val(value).html(value));
                        });

//set Text in filled dropdownlist.
for (var i = 0; i < document.getElementById('<%= dropdown.ClientID %>').options.length; i++) 
{
    if (document.getElementById('<%= dropdown.ClientID %>').options[i].text == selectedtext) {
          document.getElementById('<%= dropdown.ClientID %>').options[i].selected = true;
          return;
         }
}                

                    },
                    error: function (xhr, status, error) {
                        alert("Error in DropDown Fill.");

                    }
                });



Below method will come in .cs page.


[WebMethod(EnableSession = true)]
        public static List<string> GetValues(Guid searchObjectID)
        {
            List<string> list = new List<string>();
        //Logic to fill List
            return list;
        }



Posted in |

0 comments:

Post a Comment