Problem getting list box items added through jquery in code behind

All we need is an easy explanation of the problem, so here it is.

I have a list box control in which i populate items using Jquery by using some code like ..
$("#MylistBox").append("<option value='somevalue'>Someitem</option>

dynamically .
but in code behind when i use
MylistBox.Items is always showing Count 0 no matter how much items add.

Can anybody help me with this?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Without knowing the actual scenario… I am assuming your goal is actually to get the dynamically added items either by iterating over them or something else…

Any dynamically added DOM element that is done on the client side using JavaScript / jQuery, will not be reflected automatically to the server side. You will need to serialize them in a different way and push them back to the server side during postback. One way you can do this is by serializing all the Options of the Select element in a hidden input. You can mark the hidden input as runat=server if you wish to make it easier for you to access, otherwise use Request.Form[“…hidden input NAME attribute here… NOT ID…”] to get the value out. After you get it, you can do whatever you want with the values.

I imagine your hidden input should have some value like: “1:First Value,2:Second Value,3:…”. Just do some string manipulation to split them up and iterate over them.

Method 2

The code behind will only be aware of items that were added to the Listbox object when it was created on the server. These items will be held in ViewState and repopulated during postback.
Therefore items created dynamically on the client won’t be visible to the server side code.
If you need to get the selected value in the server side code then you are going to need to query the Request.Form["<Listbox client id>"] value during the postback.
If you need to retrieve all items added to a list box on the client I would suggest adding them all to a hidden field value as a delimited array of strings and again retrieving them using Request.Form["<hidden field id>"].

Method 3

string values = Request.Form[ListBox_SelectedSubject.UniqueID];

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply