In my ASP.NET applications, I have a server-side HTML select control.
<select id="CompanyDropDown" runat="server" style="width:330px">
</select>
I then have a link on my page that runs a JavaScript function that populates this control, and also selects the “current” item. I can see this is working because the list has all the items and the correct one is selected.
However, when the page posts back in response to a button click.
<asp:Button runat="server" ID="btnSaveCompany" Text="Save"
onclick="btnSaveCompany_Click" />
CompanyDropDown.Value is empty, and it contains no items. Any suggestions on how I can see the selected value on postback?
(Note: I tried using an ASP.NET DropDown control, but that fails postback validation when the control has items that were added after the page was rendered.)
Because items added to the list using JavaScript aren’t part of the viewstate, they cannot be retrieved server side. If you are only trying to get the selected value, put a server-side hidden field on your page and set its value using JavaScript each time the selection of the drop-down is changed:
jQuery script:
Hidden field markup:
The value of the hidden field will be carried to the server on post back. Refer to it to retrieve the value of the selected item. Be sure to add
clientidmode="static"to your drop down as well to keep the rendered id of your controls set to the id you assign in the ASPX page (i.e.,CompanyDropDownrather thanparentContainer_CompanyDropDown):Alternatively, you could use AJAX to tell the server you are adding each dynamically generated list item or changing the selection. I would only do this if you needed to maintain a list of items in addition to which one is selected.