我有一个 dropdownlist
,在填充两个 textboxes
后动态填充。
当我提交表单时,dropdownlist
即使在动态填充后也是空的。
下拉列表
<asp:DropDownList ID="DropDownListReason" runat="server" CssClass="span8">
<asp:ListItem Text="Select a reason" Value=""></asp:ListItem>
</asp:DropDownList>
渲染
protected override void Render(HtmlTextWriter writer)
{
//get the data list.
foreach (var item in dataList)
{
Page.ClientScript.RegisterForEventValidation(this.DropDownListReason.UniqueID, item.Id.ToString());
}
base.Render(writer);
}
Jquery
//get the data
$.each(response, function (key, value) {
if (value.requiresDescription) {
requiresDescription.push(value.id);
}
$("#<%= DropDownListReason.ClientID %>").append($("<option />").val(value.id).text(value.description));
});
表单提交操作是点击事件中的按钮。
如何在提交表单后保留 dropdownlist
数据?
最佳答案
您还需要在后面的代码中填写 DropDownList。后台不知道你用 javascript 填充了它,所以当你执行 PostBack 时,页面会重新加载并恢复原始状态,这不是 ListItems。
所以要么在 DropDownList 中添加所有选项。
<asp:DropDownList ID="DropDownListReason" runat="server" CssClass="span8">
<asp:ListItem Text="Select a reason" Value=""></asp:ListItem>
<asp:ListItem Text="Option 1" Value="1"></asp:ListItem>
<asp:ListItem Text="Option 2" Value="2"></asp:ListItem>
</asp:DropDownList>
或以编程方式添加它们
<asp:DropDownList ID="DropDownListReason" runat="server" AppendDataBoundItems="true" CssClass="span8">
<asp:ListItem Text="Select a reason" Value=""></asp:ListItem>
</asp:DropDownList>
DropDownListReason.Items.Insert(DropDownListReason.Items.Count(), new ListItem("Option 1", "1"));
DropDownListReason.Items.Insert(DropDownListReason.Items.Count(), new ListItem("Option 2", "2"));
现在,当您提交页面时,您可以使用 DropDownListReason.SelectedValue
读取 DropDownListReason
的值。这种在 PostBack 中保留表单值的方式称为 ViewState
。如果您要使用网络表单,您应该阅读相关内容。
关于c# - Asp .NET 下拉列表在表单提交后为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48189214/