Click here to Skip to main content
15,887,477 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi All,

I want to set the asp:dropdownlist's datasource to Javascript array.
Data is fetched in JavaScript and stored in the array. Now I want to Set the dropdownlist DataSource to Javascript Array.


function showResults(results) {
         var resultItems = [];
         var resultCount = results.features.length;
         for (var i = 0; i < resultCount; i++) {
             var featureAttributes = results.features[i].attributes;
             for (var attr in featureAttributes) {
             resultItems.push("" + attr + ":  " + featureAttributes[attr] + "<br>");
           }
           resultItems.push("<br>");
         }
         dom.byId("info").innerHTML = resultItems.join("");



<asp:DropDownList ID="ddlLocation" runat="server">
<asp:ListItem Text="XYZ" Value="XYZi">


What I have tried:

Declared the function in Script and try to bind
Posted
Updated 27-Jan-17 0:11am

1 solution

You have to do it on the client side.

One way to get the dropdownlist on the client side:
var ddl_location = document.getElementById("<%=ddlLocation.ClientID%>");


Then populate the dropdownlist with array data:
if ddl_location {
    for (var i=0; i < month.length;++i){    
        addOption(ddl_location, some_text_variable, some_value_variable);
    }
}

addOption = function(selectbox, text, value) {
    var optn = document.createElement("OPTION");
    optn.text = text;
    optn.value = value;
    selectbox.options.add(optn);  
}
 
Share this answer
 
Comments
F-ES Sitecore 27-Jan-17 6:30am    
Whilst I agree, I'd add that if you add items via javascript then your server-side control does not know about them and when you do a post-back .net will still think the dropdown is empty. If you want to build a dropdown using javascript then don't use an asp:DropDown, simply use a standard html <select>
A Atique 3-Oct-19 8:37am    
I have the same issue in my company's application. There, dropdowns are puplated using JS but when posting back, ASP.NET is taking old dropdown items and not the ones populated by JS, even SelectedValue is old one. Is there any way to let ASP know about these changes?
José Amílcar Casimiro 27-Jan-17 6:31am    
Yes, a simple <select> is better in this case.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900