Ankita
Ankita

Reputation: 83

Value of dropdownlist in asp.net disappears after changing the value of dropdownlist by javascript

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!

Upvotes: 1

Views: 1715

Answers (2)

speti43
speti43

Reputation: 3046

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.

Upvotes: 0

Icarus
Icarus

Reputation: 63970

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.

Upvotes: 3

Related Questions