c# - Asp .NET 下拉列表在表单提交后为空

标签 c# asp.net drop-down-menu

我有一个 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/

相关文章:

C# Winforms 时间轴控件(来自 WTL?)

c# - 使用正则表达式删除 css 注释

java - 在 JavaForm 中实现带有国家/地区列表的下拉菜单

c# - 仅当在计算按钮之前单击确认按钮时,如何才能显示 lblmessage?

c# - 在 Azure 数据湖中解压 .gz 文件

asp.net - 如何限制 IIS 7 中网站的 CPU 使用率?

asp.net - ASP.NET 4.5 GridView.AllowCustomPaging 属性如何使这变得更简单?

asp.net - 在 ASP.NET 应用程序中存储单例实例的最佳实践

JavaScript - 创建可更改 JavaScript 变量的 HTML 下拉菜单

c# - 带有动态下拉列表列的 GridView 中的动态 ItemTemplate