Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem getting list box items added through jquery in code behind

I have a asp.net 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?

like image 905
Jishnu A P Avatar asked Apr 09 '26 08:04

Jishnu A P


2 Answers

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.

like image 58
Jimmy Chandra Avatar answered Apr 11 '26 22:04

Jimmy Chandra


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>"].

like image 38
Andy Rose Avatar answered Apr 11 '26 20:04

Andy Rose



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!