Javascript – ASP.NET – losing selection of dropdownlist populated via javascript

asp.netdrop-down-menujavascript

I have two ASP.NET dropdownlist controls on a page. The first calls back to the server and obtains an array which is returned to the client and used to populate the second dropdownlist via javascript.
However if I make a selection in the second (and newly populated) dropdownlist and then do a postback the selection and contents of the second dropdownlist are lost. This is an issue since I need to obtain the selected value and have the contents of the list retained after the postback.

How do I fix this? I presume it's a matter of updating viewstate at some point before the postback?


The controls I'm populating are ASP.NET dropdownlists. Here is the the javascript I'm using to populate them.

Code being used is as follows (slightly cut down for brevity):

ASP.NET control I'm populating:

<asp:DropDownList ID="ddlStateCounty" runat="server" OnSelectedIndexChanged="ddlStateCounty_OnSelectedIndexChanged" AutoPostBack="true" />

Call back code that obtains comma separated list of values:

public void RaiseCallbackEvent(string eventArgument)
    {
    return "1, 2, 3";
}

Javascript population code:

function ReceiveServerData(retValue)
{ 
    var statesArray = retValue.split(',');
    var statesList = document.getElementById('{0}');

    if (statesArray.length > 0 && statesList != null)
        {
                for (var j = 0; j < statesArray.length; j++)
            {
                    var newOption = document.createElement('OPTION');
                        statesList.options.add(newOption);
            newOption.value = statesArray[j].toString().trim();
                    newOption.innerText = statesArray[j];
                }
    }
}

Best Solution

You're correct in stating that you don't have the ViewState right, which is why the values aren't populated when you post the data back to the server.

I would strongly recommend that you migrate to using the Cascading Drop Down within the ASP.NET AJAX Control Toolkit (it has both .NET 2.0 and .NET 3.5 releases), as it does what you are after and it does maintain via the postback.

Your other option would be to have an onchange event on the JavaScript-populated drop down list in which you then populate a hidden field, as that will be posted back to the server and the value of the submit will be maintained within the posted data, something like:

$addHandler('change', $get('dynamicDDL'), function () { $get('hiddenField').value = this.options[this.selectedIndex].value; });

For the demo I used the MS AJAX short-hand for adding events, etc. More info on the methods I used can be found here: http://msdn.microsoft.com/en-au/library/bb397536.aspx

Related Question