When using an ASP.NET CheckBox
(and in out case, inherited from a CheckBox
) it renders a span around the checkbox input control, this span control
I spent the last 3 hours pulling my hair to find a solution at this problem.
Here is what came out:
using System.Web.UI;
using System.Web.UI.WebControls;
/// <summary>
/// Represents a custom checkbox web control.
/// Prevents itself to be wrapped into a <span> tag when disabled.
/// </summary>
public class CustomCheckBox : CheckBox
{
/// <summary>
/// Renders the control to the specified HTML writer.
/// </summary>
/// <param name="writer">The HtmlTextWriter object that receives the control content.</param>
protected override void Render(HtmlTextWriter writer)
{
// Use custom writer
writer = new HtmlTextWriterNoSpan(writer);
// Call base class
base.Render(writer);
}
}
Along with the custom control, you'll need a custom HtmlTextWriter:
using System.IO;
using System.Web.UI;
/// <summary>
/// Represents a custom HtmlTextWriter that displays no span tag.
/// </summary>
public class HtmlTextWriterNoSpan : HtmlTextWriter
{
/// <summary>
/// Constructor.
/// </summary>
/// <param name="textWriter">Text writer.</param>
public HtmlTextWriterNoSpan(TextWriter textWriter)
: base(textWriter)
{ }
/// <summary>
/// Determines whether the specified markup element will be rendered to the requesting page.
/// </summary>
/// <param name="name">Name.</param>
/// <param name="key">Tag key.</param>
/// <returns>True if the markup element should be rendered, false otherwise.</returns>
protected override bool OnTagRender(string name, HtmlTextWriterTag key)
{
// Do not render <span> tags
if (key == HtmlTextWriterTag.Span)
return false;
// Otherwise, call the base class (always true)
return base.OnTagRender(name, key);
}
}
Just FYI, using:
checkbox.InputAttributes.Add("disabled", "disabled");
has the same effect but:
You can use the input/checkbox control directly if you don't need a label, or can put one yourself:
<input type="checkbox" id="CheckBox1" runat="server" />
<label for="CheckBox1">My Label</label>
A CSS Adapter may be able to remove the span around the checkbox/label, but I haven't seen one for that purpose.
Can you use a literal control instead? There's a big difference between these two alternatives:
<p>12345<asp:Label ID="lblMiddle" runat="server" Text="6"></asp:Label>7890</p>
<p>12345<asp:Literal ID="ltlMiddle" runat="server" Text="6"></asp:Literal>7890</p>
Why don't you remove the span using .remove with jquery ?
Try adding a constructor to your class that looks like this:
public MyControl() : base()
{
}
If you notice, controls will render as spans as default since that's what the "WebControl" uses (if you use Reflector) :
protected WebControl() : this(HtmlTextWriterTag.Span) { }
Reference: http://aspnetresources.com/blog/stripping_span_from_webcontrol
Using Jquery
<script>
$(".selector input").unwrap().addClass("cssclass");
</script>