ASP.NET – Client Side List Box

We needed to create a dropdown list that would allows us to reorder items on the list. Piece o’ cake, right? We created a composite web control with a drop down list and 3 client side buttons. A bunch of javascript managed adding the items and sorting the list. No big deal.

The interesting part didn’t happen until post back. Asp:ListBox doesn’t recognize things that are added from the client, only from the server. I thought it would work because you can do that type of things with, for example, a textbox. The different is that a textbox is an input control and a listbox is just a select control.

I created a new composite control called ClientListBox. I have know idea if I did it correctly, but it works. (I have minimal web control experience. I’m more about all of the other tiers. The composite control contains a listbox and a hidden field. As you add items to the list, the text and values are saved to the hidden field. On post back, it wipes out the list times, then creates new ones based on the contents of the hidden field.

The hidden fields stores the values as:

The IDs of the listbox and hidden fields are set dynamically based on the id of the composite control. So, if the control id is TEST, then the listbox is TEST_LB, and the hidden is TEST_HIDDEN.

Its intended use is client side script, so it gives you a known method name to retrieve the object.

If the control name is TEST, then in javascript, you can call getTEST() to obtain a reference to the object. You can then all methods like Add(text, value), etc. Conceivably, there would be MoveUp and MoveDown methods too, but we didn’t bring it that far.

ie: alert(getTEST().getCount());

getTest() is created on the server side.

function getTEST() { return new ClientSideListbox(hiddenId, listboxId); }

Is that the proper way to write a webcontrol? I have no idea. But its clean and it works.


Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: