Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent wrapping <span> tags for ASP.NET server control

I am writing various ASP.NET Server controls and am needing to remove the tags that wrap my control by default. I am aware that you can change the tag to a different tag (as in this question, How Do I Change the render behavior of my custom control from being a span) but how can you prevent it?

I am inheriting from WebControl (can also inherit from CompositeControl).

I typically get:

<span>Control output</span>

I need:

Control output

I am overriding RenderContents(HtmlTextWriter output) and the CreateChildControls() methods (across various controls). My immediate need is to address the issue using the RenderContents(HtmlTextWriter output) method.

like image 639
Program.X Avatar asked Sep 30 '10 15:09

Program.X


3 Answers

What about this?

    public override void RenderBeginTag(HtmlTextWriter writer)
    {
        writer.Write("");
    }

    public override void RenderEndTag(HtmlTextWriter writer)
    {
        writer.Write("");
    }
like image 153
Claudio Redi Avatar answered Nov 09 '22 07:11

Claudio Redi


A more elegant way to do this is by using the contrustor of WebControl (By default this is called with the HtmlTextWriterTag.Span)

public MyWebControl() : base(HtmlTextWriterTag.Div){}

and override the RenderBeginTag method to add custom attributes or other stuff:

public override void RenderBeginTag(HtmlTextWriter writer)
    {
        writer.AddAttribute("class", "SomeClassName");
        base.RenderBeginTag(writer);
    }
like image 44
Jim Bosch Avatar answered Nov 09 '22 07:11

Jim Bosch


I was experiencing the same issue. In my case I was overriding the methods:

protected override void OnPreRender(EventArgs e)
    { /* Insert the control's stylesheet on the page */ }

and

protected override void RenderContents(HtmlTextWriter output)
        { /* Control rendering here, <span> tag will show up */ }

To prevent this, I simply replaced the RenderContents override with the following:

protected override void Render(HtmlTextWriter output)
        { /* Control rendering, no <span> tag */ }

Hope this helps.

like image 4
Mike Gilmore Avatar answered Nov 09 '22 08:11

Mike Gilmore