格式化复选框?

时间:2012-05-14 14:28:00

标签: c# asp.net .net css checkbox

我正在使用.net构建的网站,我试图输出我的标记......

<span class="check-input">
     <!-- Terms -->
     <input type="checkbox" id="terms" class="terms checkbox">
     <label for="terms">I agree to the terms and conditions</label>
     <input type="checkbox" id="age" class="age checkbox">
     <label for="age">I am over 18 years old</label>
     </span>

只有我的开发人员实施的代码才是......

<!-- Terms -->
       <asp:CheckBox ID="CB_Agree" 
       Text="I agree to the terms and conditions" runat="server" TabIndex="4" />

       <asp:CheckBox ID="CB_Age" 
       Text="I am over 18 years old" runat="server" TabIndex="5" />

这是将我的数据输出为......

<span class="check-input">
<!-- Terms -->
<span class="terms checkbox">
    <input type="checkbox" tabindex="4" name="ctl00$ContentPlaceHolder1$CB_Agree" id="ctl00_ContentPlaceHolder1_CB_Agree">
    <label for="ctl00_ContentPlaceHolder1_CB_Agree">I agree to the terms and conditions</label>
</span>
<span class="age checkbox">
    <input type="checkbox" tabindex="5" name="ctl00$ContentPlaceHolder1$CB_Age" id="ctl00_ContentPlaceHolder1_CB_Age">
    <label for="ctl00_ContentPlaceHolder1_CB_Age">I am over 18 years old</label>
</span>
</span>

3 个答案:

答案 0 :(得分:5)

然后您(或您的开发人员)需要将CssClass属性添加到复选框。

例如:

<asp:CheckBox ID="CB_Agree" 
       CssClass="terms checkbox"
       Text="I agree to the terms and conditions" runat="server" TabIndex="4" />

它还有InputAttributes来控制复选框的布局和范围的LabelAttributes属性。

因此,您可以通过以下方式在代码隐藏中应用不同的背景颜色:

CB_Agree.InputAttributes.CssStyle.Add("background-color", "Red");
CB_Agree.LabelAttributes.CssStyle.Add("background-color", "Green");

答案 1 :(得分:1)

您将无法控制名称的输出方式,但您可以控制输出ID的方式。一种方法是将ClientIDMode ="Static"添加到标记中的控件中,如下所示:

<asp:CheckBox ID="CB_Agree"  ClientIDMode ="Static"
   Text="I agree to the terms and conditions" runat="server" TabIndex="4" />
蒂姆让我意识到你的风格也有问题。为此,您需要添加CssClass="your_class your_other_class"

<asp:CheckBox ID="CB_Agree"  ClientIDMode ="Static" CssClass="terms checkbox"
   Text="I agree to the terms and conditions" runat="server" TabIndex="4" />

答案 2 :(得分:0)

  
    

Cleaner HTML Markup with ASP.NET 4 Web Forms - Client IDs (VS 2010 and .NET 4.0 Series)

  

如果您使用ASP.NET 4.0,那么您可以在控件上使用值static的{​​{3}},并且ID不会更改。

否则,您可以使用文字输出元素本身或仅输出其值。在你的页面上你有:

<input type="hidden" id="ppID" value='<asp:Literal ID="ppIDValue" runat="server" />' />

要将css类应用于控件,请使用服务器端控件的ClientIDMode属性:

 <asp:CheckBox ID="CB_Agree" 
       Text="I agree to the terms and conditions" runat="server" TabIndex="4"
       CssClass="terms checkbox"   />

参考:CssClass