Options added to <select> by javascript lost in postback

前端 未结 2 891
无人共我
无人共我 2020-12-11 01:17

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:

         


        
2条回答
  •  春和景丽
    2020-12-11 01:52

    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

提交回复
热议问题