views:

66

answers:

2

Hi everyone,

I have an ASP.Net page with two ListBox components, rendered in the browser as <select> lists. I'm using jQuery to move elements from one list to another by manipulating the DOM. I then select all elements with the mouse and postback the form. That way, all the list elements are posted with the form.

When I submit the form, in my button_save() event handler, the Request.Form[<<listbox ID>>] values are correct. However the ListBox controls themselves, specifically their Items collections, do not reflect my changes.

I've also used Fiddler to modify the select items and submit the form. Same as above, the ListBox values are no different, though the Request.Form values are. Would anyone know what's going on or what incorrect assumptions I'm making?

+1  A: 

I believe the problem is that the server constructs a ListBox object that is unaware of changes made to the select box on the client side. That is to say, it uses the ASP.NET markup to construct the list of items, rather than the information submitted from the request.

I'm not aware of any workaround to this, other than accessing the Request.Form values directly.

Ender
+1  A: 

I believe the root issue is: the ListBox's options are stored in the page's viewstate. When you use client-side javascript / jquery to modify the list's contents, those changes are not reflected in the viewstate. Thus, when you postback, ASP.NET uses the viewstate to build the lists for your codebehind, and your client-side changes are lost.

One way to resolve this would be to manipulate the lists' content via postback, instead of client-side (javascript/jquery). By doing it that way, all changes to the listboxes are incorporated into the viewstate, and thus will remain consistent for each postback.

I am a big fan of jquery (much moreso than postbacks or MS-Ajax/partial-postbacks), so I completely understand that this approach may not be very appealing. Unfortunately, it's the only one I can think of right now. Maybe other stackoverflow'ers will have better alternatives.

mikemanne
Thanks Mike. Your ViewState theory sounds good, it's just that I thought the ASP.Net pipeline loaded ViewState data into the controls at the start, then later in the cycle loaded postback data into them. So the posted form data should get in there near the end. That's how it's supposed to work at least. (We're manipulating the list data via postback right now and were hoping to use AJAX/jQuery instead.)
larryq
When you use jQuery to add/remove <option>s from your <select> lists, those changes are likely not reflected in the ViewState at all. I believe that's where your error is occurring. I don't think it's a matter of when the ViewState gets loaded during the page lifecycle.
mikemanne