On my webpage, I have two ASP.NET dropdownlist controls. The first dropdownlist retrieves an array from the server and uses it to populate the second dropdownlist through javascript. However, when I select an option in the second dropdownlist and then perform a postback, the selection and contents of the second dropdownlist disappear. This is problematic because I need to retain the selected value and keep the list's contents after the postback.
How can I solve this issue? Do I need to update the viewstate before the postback?
The dropdownlists I am populating are ASP.NET controls. Below is the snippet of javascript code that I use to populate them.
The code used is as shown below:
ASP.NET control being populated:
<asp:DropDownList ID="ddlStateCounty" runat="server" OnSelectedIndexChanged="ddlStateCounty_OnSelectedIndexChanged" AutoPostBack="true" />
Callback function that retrieves comma-separated list of values:
public void RaiseCallbackEvent(string eventArgument)
{
return "1, 2, 3";
}
Javascript code for population:
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];
}
}
}