How Do I Change the render behavior of my custom control from being a span

喜夏-厌秋 提交于 2019-12-04 03:32:04

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.

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.

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; }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!