Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Options added to <select> by javascript lost in postback

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)
like image 383
Billy Avatar asked Aug 13 '09 10:08

Billy


2 Answers

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.

Possible Workaround

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

like image 192
Kirtan Avatar answered Oct 06 '22 02:10

Kirtan


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.

like image 23
Guffa Avatar answered Oct 06 '22 02:10

Guffa