【问题标题】:load a drop down box based on selected option in first drop down box根据第一个下拉框中的选定选项加载下拉框
【发布时间】:2014-01-15 06:13:11
【问题描述】:

我想根据我在下拉框 1 中所做的选择显示第二个下拉框 我是 asp.net 的新手,在 asp.net 中使用 c#,我不知道 java script 和 jquery,所以我知道 html 和 CSS,代码如下:

      <asp:DropDownList ID="typeselect" runat="server" AutoPostBack="true" OnSelectedIndexChanged="typeselect_SelectedIndexChanged">
          <asp:ListItem Selected="True" Text="cash" Value="0"></asp:ListItem>
          <asp:ListItem Text="Traveller's cheque" Value="1"></asp:ListItem>
      </asp:DropDownList>

当我从上面的代码中选择旅行支票时,我想获得另一个与我选择现金时不同的下拉框。当从以上列表项中选择现金时,以下下拉框是默认的。

当用户选择旅行支票时,我如何显示以上代码? 请帮我实现这个.. 提前谢谢你..

【问题讨论】:

  • 你想用jQuery还是C#来实现它?
  • 好的。在下面提供了答案,请检查

标签: c# asp.net


【解决方案1】:

在您的typeselect_SelectedIndexChanged event 中。

    protected void typeselect_SelectedIndexChanged(object sender, EventArgs e)
    {
       try{
        seconddropdown.Items.Clear();
        IList<InfoContainer> info = getInfoBasedOnSelected(typeselect.Value);
        seconddropdown.DataTextField = "name";
        seconddropdown.DataValueField = "value";
        seconddropdown.DataSource = info;
        seconddropdown.DataBind();
        }catch(Exception ex)
        {
          throw new ApplicationException("ERROR :", ex);
        }
   }

不要忘记为typeselect 下拉设置设置AutoPostBack="True"

【讨论】:

  • 一个空的 catch 块是不行的!
  • 你在上面的代码中使用的那个 infocontainer 是什么......你能简要介绍一下这个类的含义以及它应该包含哪些数据吗?
  • @user3181351 它应该包含基于第一个下拉值的第二个下拉列表的详细信息
  • @user3181351:如果需要,您也可以使用 sql 查询来检索数据
【解决方案2】:

我认为 jQuery 方法会对此有好处,因为它对于单个下拉列表的回发整个内容并不好。

【讨论】:

    【解决方案3】:

    您至少有两个选择
    1)处理 typeselect_SelectedIndexChanged 事件(就像你所做的那样)。有关更多示例,请参阅此页面:http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.selectedindexchanged(v=vs.110).aspx 不好的是它会在服务器上发布并刷新您的页面。如果你想避免这种情况,你必须使用选项二。
    2)使用ajax获取网页的部分数据。我认为这个例子应该接近你的需要:Partial postback of page with dropdownlist using AJAX on MVC3 page EF4

    【讨论】:

      【解决方案4】:

      【讨论】:

        【解决方案5】:

        处理你下拉的SelectedIndexChanged事件:

        this.typeselect.SelectedIndexChanged += new EventHandler(typeselect_SelectedIndexChanged);
        

        之后,您可以转到typeselect_SelectedIndexChanged 并检查选择了哪个值。如果是“旅行支票”,您可以绑定第二个下拉菜单:

        otherDropdown.DataTextField = "Name";
        otherDropdown.DataValueField = "ID";
        otherDropdown.DataSource = IList<T>;
        otherDropdown.DataBind();
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-12-01
          • 1970-01-01
          • 1970-01-01
          • 2017-09-19
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多