send <style> info from custom server asp ele

2019-05-29 01:44发布

问题:

I want send to output CSS info in style blocks

      protected override void RenderContents(HtmlTextWriter output)
    {
      ...
      output.Write("<style> .... ");
    }

But this block cant be nested in div block .I must place it in head.How can I do it or is there another approach?

回答1:

The this.Page.Header.Stylesheet.CreateStyleRule method lets you add styles to the <head>. However, the CSS attributes that you can specify are limited to those supported by the Style class. (You can derive your own class from Style if you need additional attributes.)

C# example:

protected override void OnPreRender(EventArgs e)
{
    base.OnPreRender(e);

    // Create a Style object for the body of the page.
    Style bodyStyle = new Style();

    bodyStyle.ForeColor = System.Drawing.Color.Blue;
    bodyStyle.BackColor = System.Drawing.Color.LightGray;

    // Add the style rule named bodyStyle to the header 
    // of the current page. The rule is for the body HTML element.
    this.Page.Header.StyleSheet.CreateStyleRule(bodyStyle, null, "body");
}


回答2:

Derive from System.Web.UI.Control directly and override the Render method, instead of deriving from (what I assume is) System.Web.IO.WebControls.WebControl.