I have posted earlier on moving items from one ListBox to another. We use jQuery to do that. Listbox posts only the selected values to the server.  In our case, we are not making any selections. But rather moving the Listbox options. We need a way for the server to know that the options have changed. So, I have come up with a solution in this post.

ASP.NET UI

The HTML code is same as before. We move options between Listboxes, list1 and list2. There are four buttons to move the options.

  1. Add: add selected options in list1 to list2
  2. Remove: remove selected options from list2 to list1
  3. Add All: adds all options in list1 to list2
  4. Remove All: removes all options in list2 to list1

In addition, we have two hidden fields. I will explain the use of these hidden fields below.

jQuery

The jQuery code for moving items is the same as explained in the previous post.

We have a submit method which does a few extra things. The hidden fields are stored with the Listbox options in a special format.

<selected-value>;<option-1-value>,<option-2-value>,<option-3-value>,

Server-side syncing

The hidden fields are posted to the server on submit. On the server side, we sync up the state of the ListBox from these hidden fields.

There is nothing special about the above code. It is a lot of string parsing. We parse the string within the hidden field. And populate the Listbox options. In addition, we select the list item. The Listbox server control is in sync with the changes on the browser.

Move items from one Listbox to another using jQuery – Part 2
Tagged on: