How Do I Change the render behavior of my custom c

2019-04-06 23:25发布

问题:

When writing a custom control it always rendered as an HTML span element. How can I change it for example to a div?

回答1:

Derive your control from WebControl as follows:

public class MyCustomControl : WebControl {
    public MyCustomControl() : base(HtmlTextWriterTag.Div) {}
}

That is, use the base class constructor that accepts the tag to use.



回答2:

If you derive from CompositeControl there is no constructor that takes a tag type. You can override TagKey (I haven't tried it), but a more flexible option is to override the RenderBeginTag method and make it do what you want. The base class renders a "span" opening element, but you don't have to call the base class method. You don't have to call anything if you don't want anything rendered (in which case also override RenderEndTag and don't call anything there either). For example,

public override void RenderBeginTag(HtmlTextWriter writer)
    {
        writer.AddAttribute(HtmlTextWriterAttribute.Class, "reportViewer");
        writer.AddAttribute(HtmlTextWriterAttribute.Id, "QueryViewerWrapper");
        writer.RenderBeginTag(HtmlTextWriterTag.Div); 
    }

This code produces

<div class="reportViewer" id="QueryViewerWrapper">

which is exactly what I needed for this particular composite control of mine, a div with a class to wrap a ReportViewer control. I include the ID just to make the output easier to spot.



回答3:

I normally have my own base class that all my composite controls inherit from. One of the properties I add to this is a ContainerElement. Publicly exposed, the developer can choose what ever outer element they want. Internally it sets the TagKey property which governs this rendering on the base control. All the following to your control/base class.

You just need to set HTMLContainerElement which will have the inteli-help of all the items in the HtmlTextWriterTag enumeration.

/// <summary>
/// Local variable for storing what the container element for the rendered control will be.
/// </summary>
private HtmlTextWriterTag hosTagKey = HtmlTextWriterTag.Span;

/// <summary>
/// HTMLContanerElement is the tag key used to set the controls outer html control which appears in the markup.
/// The default is a span, but you can change this to be any HTML control you choose.
/// </summary>
public HtmlTextWriterTag HTMLContainerElement
{
  get { return this.hosTagKey; }
  set { this.hosTagKey = value; }
}

/// <summary>
/// Makes it so this control is a "div" element instead of the
/// standard "span" element.
/// </summary>
protected override HtmlTextWriterTag TagKey
{
  get { return this.hosTagKey; }
}