views:

2297

answers:

2

I've got a dropdown list that is being populated via a webservice using ASP>NET AJAX. On the success callback of the method in javascript, I'm populating the dropdown via a loop:

function populateDropDown(dropdownId, list, enable, showCount)
{
    var dropdown = $get(dropdownId);
    dropdown.options.length = 1;    
    for (var i = 0; i < list.length; i++) {
        var opt = document.createElement("option");
        if (showCount) {
      opt.text = list[i].Name + ' (' + list[i].ChildCount + ')';
        } else {
      opt.text = list[i].Name;
     }
        opt.value = list[i].Name;
        dropdown.options.add(opt);
    }
    dropdown.disabled = !enable;    
}

However when I submit the form that this control is on, the control's list is always empty on postback. How do I get the populated lists data to persist over postback?

Edit: Maybe I'm coming at this backwards. A better question would probably be, how do I populate a dropdown list from a webservice without having to use an updatepanel due to the full page lifecycle it has to run through?

+3  A: 

You need to use Request.Form for this - you can't encrypt ViewState on the fly from the client - it would defeat the whole point of it :).

Edit: Responding to your Edit :) the Page Lifecycle is the thing that allows you to use the ViewState persistence in the first place. The control tree is handled there and, well, there's just no getting around it.

Request.Form is a perfectly viable way to do this - it will tell you the value of the selection. If you want to know all of the values, you could do some type of serialization to a hidden control.

Ugly, yes, But that's why god (some call him ScottGu) invented ASP.NET MVC :).

Rob Conery
Yeah, I wish I could use MVC! I've gone with the hidden field option, using Page.ClientScript.RegisterHiddenField to set it up. I've created a class that inherits from Dropdownlist that overrides the SelectedValue to load from the Request.Form
Glenn Slaven
+3  A: 

Although I'm not really sure how it does it the CascadingDropDown in the AJAX Control Toolkit does support this.

This is the line that appears to do it:

AjaxControlToolkit.CascadingDropDownBehavior.callBaseMethod(this, 'set_ClientState', [ this._selectedValue+':::'+text ]);

But the simplest idea would be to put the selected value into a hidden input field for the postback event.

Slace