为HTMLInputCheckbox获取相同的名称

时间:2012-10-19 15:55:23

标签: asp.net webforms

这里有超级新手问题。我正在尝试自学Web表单,所以我正在尝试runat="server"属性。所以这是我的代码:

<p>
Number of items:
<input type="checkbox" name="custom_name_qty" value="25" runat="server" />25
<input type="checkbox" name="custom_name_qty" value="50" runat="server" />50
<input type="checkbox" name="custom_name_qty" value="75" runat="server" />75
<input type="checkbox" name="custom_name_qty" value="100" runat="server" />100
<input type="checkbox" name="custom_name_qty" value="Other" runat="server" />Other
</p>

以下是生成的内容:

<p>
Number of items:
<input name="ctl01" type="checkbox" value="25" />25
<input name="ctl02" type="checkbox" value="50" />50
<input name="ctl03" type="checkbox" value="75" />75
<input name="ctl04" type="checkbox" value="100" />100
<input name="ctl05" type="checkbox" value="Other" />Other

因此,我的复选框组具有相同的名称,并为它们分别命名。为什么是这样?即使我给它们单独的名称(在每个名称的末尾添加一个整数),它们仍然会被重命名。

我在这里做错了什么?如何让复选框输出相同的名称?我怎么能得到复选框来保留我给他们的名字?我宁愿使用我给出的名字而不是“ctl01”。

1 个答案:

答案 0 :(得分:1)

你没有做错任何事,那是the default behaviour of asp.net.通过<asp:CheckListBox />控制实现了这一点:CheckListBox

  <asp:CheckBoxList id="checkboxlist1" 
       AutoPostBack="True"
       CellPadding="5"
       CellSpacing="5"
       RepeatColumns="2"
       RepeatDirection="Vertical"
       RepeatLayout="Flow"
       TextAlign="Right"
       OnSelectedIndexChanged="Check_Clicked"
       runat="server">

     <asp:ListItem>Item 1</asp:ListItem>
     <asp:ListItem>Item 2</asp:ListItem>
     <asp:ListItem>Item 3</asp:ListItem>
     <asp:ListItem>Item 4</asp:ListItem>
     <asp:ListItem>Item 5</asp:ListItem>
     <asp:ListItem>Item 6</asp:ListItem>

  </asp:CheckBoxList>

显示了如何手动添加项目。您还可以从数据库中填充检查列表

  System.Data.DataTable dtOptions = GetValuesFromDataBase();
  checkboxlist1.DataSource = dtOptions;
  checkboxlist1.DataBind();

<强>更新

在Asp.Net 4及更高版本中,您可以更好地控制how control ID are generated (e.g. AutoID, Static, Predictable, Inherit)