Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
584 views
in Technique[技术] by (71.8m points)

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...