ASP.NET 2.0 dynamically adds styles to a page in a control

I need to add a page from a user control. I cannot use a stylesheet (.css) because I use url (...) and you need to resolve the URL.

Now I am doing:

Page.Header.Controls.Add(new LiteralControl("<style type='text/css'>.xyz { color: blue; }</style>")); 

But I hope for something more elegant touch?

+6
custom-server-controls
source share
3 answers

I think this is not a bad solution to the problem. If you have an external stylesheet file, this piece of code will work:

 HtmlLink cssRef = new HtmlLink(); cssRef.Href = "styles/main.css"; cssRef.Attributes["rel"] = "stylesheet"; cssRef.Attributes["type"] = "text/css"; Page.Header.Controls.Add(cssRef); 

Another idea is to write your own ASP.NET ServerControl "HtmlInlineStyle" so you can call it that way (script tags will be executed by your server control):

 Page.Header.Controls.Add( New HtmlInlineStyle(".xyz { width:300px;padding-left:10px }"); 

This blog post and the comments show some alternatives (ScriptManager.RegisterClientScriptBlock). But, in my opinion, your decision is in order.

+3
source share

Here is another way ... For example:

Part of parent ASPX:

 <div id="div1" class="xyz" style="width: 40px; height: 40px;"> <span>abc</span> </div> 

Inside the control:

 Dim xyzStyle As New Style() xyzStyle.CssClass = "xyz" xyzStyle.BackColor = Drawing.Color.LightBlue Page.Header.StyleSheet.CreateStyleRule(xyzStyle, Nothing, ".xyz") 

Note that this assumes that the parent ASPX page has the class attribute set for the target control. If not, you will need to combine the style with the control using the MergeStyle method. (This requires the control to be runat="server" ).

This code displays the following result: (Showing the entire source for your convenience)

 <html> <head> <title>Untitled Page </title> <style type="text/css"> .xyz { background-color:LightBlue; } </style> </head> <body> <form name="form1" method="post" action="MyPage.aspx" id="form1"> <div id="div1" class="xyz" style="width: 40px; height: 40px;"> <span>abc</span> </div> </form> </body> </html> 
+1
source share

I create my own class and inherit the style, with my own dictionary for attributes that the Style class does not include by default. Here is a brief example ...

  protected override void FillStyleAttributes(CssStyleCollection attributes, IUrlResolutionService urlResolver) { Dictionary<String, String> _styles = new Dictionary<string, string>(); _styles.Add("display", "inline-block"); foreach (String s in _styles.Keys) { attributes[s] = (String)_styles[s]; } base.FillStyleAttributes(attributes, urlResolver); } 
0
source share

All Articles