添加到< select>的选项通过javascript在回发中丢失 [英] Options added to <select> by javascript lost in postback

查看:148
本文介绍了添加到< select>的选项通过javascript在回发中丢失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在客户端通过javascript向select元素添加了一些选项,但无法在回发中获取。

I added some options to the select element by javascript in client side and cannot get it in postback.

我该怎么办?

用于添加选项的代码:

<asp:DropDownList ID="ddlProduct" runat="server"></asp:DropDownList>

var ddlProduct = "#"+"<%= ddlProduct.ClientID %>";

$(ddlProduct).append($("<option></option>").html(product_name)


推荐答案

使用JavaScript添加到下拉列表的选项永远不会到达服务器端,更不用说在回发期间保留。选项存储在您正在使用客户端的DOM修改下拉列表,但是ViewState呢?您没有修改它,因此ASP.NET不会知道对下拉列表进行任何更改,当它重新加载时ViewState下拉列表的状态。

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.

您可以将项目存储在JSON格式的字符串中,并使用.NET Framework的 DataContractJsonSerializer类(如果您使用的是.NET Framework> = 3.5)在服务器端。如果您不使用.NET Framework 3.5,则可以使用分隔符 - text1,text2 | value1,value2

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

这篇关于添加到&lt; select&gt;的选项通过javascript在回发中丢失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆