简体   繁体   中英

Add Attributes to root HTML Element of a Custom Control

public class CustCtl : WebControl
{
    protected override System.Web.UI.HtmlTextWriterTag TagKey
    {
        get
        {
            return HtmlTextWriterTag.Div;
        }
    }       
}

With this bare bones control, it would render the root element as a Div tag. But how can I add attributes to that root HTML element that this control will render ... such as a style or id.

Thanks! =D

You would be able to do something like this within the OnPreRender event

public class CustCtl : WebControl
{
    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);

        WebControl parent = Parent as WebControl;
        if (parent != null)
        {
            parent.Attributes.Add("key", "value");
        }
    }
}

If you have your HtmlTextWriter , you can first add some attributes, before rendering a tag. For example:

public void writeDivWithStyle(HtmlTextWriter writer, string style)
{
    writer.AddAttribute(HtmlTextWriterAttribute.Style, style);
    writer.RenderBeginTag(HtmlTextWriterTag.Div);

    // more code here

    writer.RenderEndTag(); // close the DIV
}

You should be able to use:

CONTROL.Attribute.Add("..") //not the correct syntax

see this link

EDIT: sample usage

Control control = this.FindControl("body");
HtmlControl divControl = new HtmlGenericControl("div");
divControl.Attributes.Add("id","myid");
divControl.Attributes.Add("class","myclass");
control.Controls.Add(divControl);

I found this method while looking at the API.

This worked just fine for me and seemed the most appropriate place to put it. Just simply override.

public override void RenderBeginTag(HtmlTextWriter writer)
{
    writer.AddAttribute(HtmlTextWriterAttribute.Class, "[^_^]");
    base.RenderBeginTag(writer);
}

[Edit, after all comments] Simply, Attributes.Add("key", "value"); in OnPreRender method works

I think that the most appropriate method or event to override is :

protected override void AddAttributesToRender(HtmlTextWriter writer)
{
    writer.AddAttribute("Key", "Value");
    base.AddAttributesToRender(writer);
}

Check the msdn .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM