1

In my application, I have created an ajax autocompelete extender text box.Once the user chooses the value, I want to insert that value in my dropdownlist. The code for that purpose is:

function GetCode(source, eventArgs) {
         var hfield = $get('<%=this.HiddenID.ClientID%>');
         hfield.value = eventArgs.get_value();

       //hfield has the value selected in the autocomplete text box

        var abc = document.getElementById('<% =DropDownList2.ClientID %>');

         for (var i = 0; i < abc.length ; i++) {
             alert(abc.options[i].value);
             if (abc.options[i].value == hfield.value) {
                 abc.options[i].selected = true;
                 break;
             }
         }
     }

The problem here is: My value is not showing in the dropdownlist. When I tried to debug the code, I realized that the value does come in the dropdownlist but when this code exits, the value disappears from the dropdownlist.

I have no idea why the values are disappearing! Please help! Thank you!

2 Answers 2

3

It's dissapearing because you are binding the data on the server-side initially and when you make the ajax request to insert the new record into the dropdownlist, the ViewState for the DropDownList had no knowledge of this new value and therefore renders what it had before.

Sign up to request clarification or add additional context in comments.

2 Comments

ok now I get it! But then what should I do to make my values not disappear?
The way to do it is how @speti43 suggested: add a Hidden element and set its value to whatever the selected value is in the dropdown. After postback, restore this value yourself to the dropdown. You basically have to manage the state manually, unfortunately :-/
0

If you want to modify a server side dropdownlist's element collection on client-side by javascript, you can get eventvalidation error on next postback. It would be dangerous if this behaviour wouldn't be because you could modify these controls collection by xss attack, and submit your extra added value to the server.

2 Comments

I am not adding any extra value to my dropdown list.I am just trying to change the selection inside the dropdownlist by javascript. Is there some other way to do this?
Yeah, do it on server side. You have the value on server side, so you can make there the selection. Or on every page_load check your hiddenfield's value, and set there the selected value of dropdown. But this would be like you want to manage "viewstate" by manually.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.