I added some options to the select element by javascript in client side and cannot get it in postback.
What should I do?
Code used to add options:
<asp:DropDownList ID="ddlProduct" runat="server"></asp:DropDownList>
var ddlProduct = "#"+"<%= ddlProduct.ClientID %>";
$(ddlProduct).append($("<option></option>").html(product_name)
The options added to a dropdown list using JavaScript WILL NEVER reach the server side let alone be preserved during postback. The options are stored in the ViewState. You are modifying the dropdown list using DOM on the client side, but what about ViewState? You are not modifying it, so ASP.NET won't know that any change has been done to the dropdown list, when it reloads the state of the dropdown list from the ViewState.
One way is to use hidden variables to store the values that you added to the dropdown list. When the control goes to the server side, you can check the value of this hidden field and add the items to the dropdown list, if necessary.
You can store the items in JSON-formatted-string, and parse this string using .NET Framework's DataContractJsonSerializer Class (if you are using .NET Framework >= 3.5) on the server side. If you are not using .NET Framework 3.5, then you can use seperators like - text1,text2|value1,value2
The only data that is sent back to the server from the select
tag is the value of the selected item. The options that you add are not sent back to the server.
The server controls in ASP.NET uses viewstate to keep the ListItem
objects that form the option
tags in the rendered select
tag. The viewstate is usually send in a separate hidden field so that it's returned to the server when the form is posted.
You could use a similar technique for the options that you add, putting them also in a hidden field, which you then can process in the server code to create ListItem
objects for the items to put in the DropDown
control.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With