Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
572 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...