Learning While Aging

AJAX Drop Down List – Part Three

In the part one and part two of AJAX Drop Down List tutorial, I have described how to populate a drop down list with plain string data and XML string data respectively. If you followed the first two parts of the tutorial and built your drop down list, you will probably notice that you cannot use “ddlChildList.SelectedValue” to retrieve the value from the drop down list. The reason is that the drop down list is built by the client, so the server is not aware of the change, thus upon post backs the drop down list is reset to an empty list. The SelectedValue property of the drop down list, therefore, will always return an empty string.

How to solve this problem? First, we need to save all the values of the drop down list; then in Page_Init event handler, we will use those values to re-populate the drop down list.

We will use a HTML hidden field to store the drop down list values, then re-populate the drop down list in Page_Init event handler.

1. Switch to HTML view of the client side page ProductList.aspx, and add the following line of code:

<INPUT Type=”hidden” id=”hiddenChildList” runat=”server”>

2. In JavaScript code, we assign the value of responseText or responseXML to the hidden value, depending on what data structure you would like to use. The tricky thing is if you use XML as the output data, then you have to convert it to a string before you can assign it to the hidden value. With JavaScipt, we can use XMLSerializer object to convert XML data to string, but IE does not like XMLSerializer object and will generate an error. With IE, we use responseXML.xml to convert it to string. Here is the segment of the JavaScript code:

……

var hList = document.getElementById(“hiddenChildList”);
hList.value= ”;
try
{

hList.value = (new XMLSerializer()).serializeToString(http_request.responseXML.documentElement);

}
catch (e)
{

try
{

hList.value = http_request.responseXML.xml;

}
catch (e)
{

lbl.innerHTML = “No software is available for this verdor.”;

}

}

……

3. In Page_Init event handler of the client side page, the child drop down list is re-populated.

Here is the code (dealing with XML data):

Re-populate a drop down list with Page_Init event handler

Now, we can access the child drop down list selected value with the SelectedValue property:

productID = ddlChildList.SelectedValue

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x