如何添加可编辑的' ASP.NET中的复选框?

时间:2016-12-04 17:46:39

标签: jquery asp.net ajax checkbox dynamic

我想实现这样的东西 enter image description here 如果'其他'选中复选框,与其相邻的文本变为可编辑或添加新复选框,其中复选框的文本可根据用户选择进行编辑。它可以在ASP.NET中实现吗?

我尝试了什么

我已经使用jQuery动态添加了复选框,但这些在ASp.NET代码中无法访问,因此我无法使用它。我还查看了onselectedindex事件,但找不到可以使用可编辑文本'将复选框添加到CheckBoxList的方法。

Your favour subject?<br><br>
<input type=checkbox > <label>Physics</label>
<input type=checkbox > <label>chemistry</label>
<input type=checkbox > <label>Math</label>
<input type=checkbox > <label>Other</label> _______________________

我想要一些非常接近this jsfiddle的东西,问题是jQuery的东西在服务器端无法访问。我想我应该能够只使用Ajax将新创建的复选框和旧复选框一起发送到数据库以保存它们,但这会使我的逻辑变得复杂,因为我在页面上还有其他控件。

1 个答案:

答案 0 :(得分:0)

您应该使用CheckBoxList控件。将其添加到页面并向CheckBoxList添加OnSelectedIndexChanged并将AutoPostBack设置为true

<asp:CheckBoxList ID="CheckBoxList1" runat="server" OnSelectedIndexChanged="CheckBoxList1_SelectedIndexChanged" AutoPostBack="true">
    <asp:ListItem Text="Physics" Value="1"></asp:ListItem>
    <asp:ListItem Text="Chemistry" Value="2"></asp:ListItem>
    <asp:ListItem Text="Math" Value="3"></asp:ListItem>
    <asp:ListItem Text="Other" Value="0"></asp:ListItem>
</asp:CheckBoxList>

<asp:TextBox ID="TextBox1" runat="server" Visible="false"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="RequiredFieldValidator" ControlToValidate="TextBox1" Enabled="false"></asp:RequiredFieldValidator>

然后在代码背后

protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)
{
    TextBox1.Visible = false;
    RequiredFieldValidator1.Enabled = false;

    foreach (ListItem item in CheckBoxList1.Items)
    {
        if (item.Value == "0" && item.Selected == true)
        {
            TextBox1.Visible = true;
            RequiredFieldValidator1.Enabled = true;
        }
    }
}