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='somevalu开发者_Python百科e'>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?
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.
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>"].
string values = Request.Form[ListBox_SelectedSubject.UniqueID];
精彩评论