views:

42

answers:

2

So I have a cascading dropdown of sorts, but using List Boxes. When an item is selected in the first ListBox, the second ListBox is populated with items based on the first selection (this is done using a jQuery AJAX call). Here's what I got:

$('#<%= lbEvents.ClientID %>').change(function() {
    var selectedValues = $('#<%= lbEvents.ClientID %>').val();
    var json = '{ events: [' + selectedValues.join(',') + '] }';

    $.ajax({
        type: "POST",
        url: 'Default.aspx/PopulateAttendees',
        data: json,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnAttendeesPopulated
    });
});



function OnAttendeesPopulated(response) {
    var attendees = response.d;
    var attendeesList = $("#<%= lbAttendees.ClientID %>");

    attendeesList.children().remove();

    $.each(attendees, function() {
        attendeesList.append($("<option></option>").val(this['Value']).html(this['Text']));
    });
}


//Populated on PageLoad
<asp:ListBox ID="lbEvents" runat="server" SelectionMode="Multiple" />

<asp:ListBox ID="lbAttendees" runat="server" SelectionMode="Multiple" />

<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />

At first, I was getting an error on the button's click event because lbAttendees was being loaded dynamically, so I had to set EnableEventValidation to false.

I don't get the error now, but in the button's click event, I can only access the data in lbEvents, but not lbAttendees; lbAttendees is empty in the click event. I assume I need to store the data from lbAttendees in ViewState.

How can I store the data from lbAttendees in ViewState so I can access it in the click event?

+1  A: 

You can't really do this (at least not easily). The issue here is that ajax and asp.net forms don't really mix well together. As I see it you you have two options:

  • Hook into the 2nd listbox with JavaScript and then use AJAX with some api (REST?) to save the items as they are clicked on. (Basically make the 2nd listbox 100% AJAX enabled.) This is a hard solution -- you have to deal with lots of UI events and use case, but very cool if you get it working.

  • Add some JavaScript which runs when the button is clicked this code will write the selected values to a hidden textbox. Then your server-side code can read the values (comma separated) out of the hidden textbox.

Hogan
I used the second option, adding the selected values to a hidden field. Thanks.
Steven
A: 

You can access the form data for that control directly, by using:

Request.Form[lbAttendees.UniqueID]

That will contain the value of the selected option. As you're dealing with the raw form data, you'll only be able to get the value not the text or other options.

Matthew Jacobs