views:

908

answers:

2

I need to add to the page from within a custom control. I can't use a stylesheet (.css) because I'm using a url(...) and need to resolve the url.

Right now I'm doing:

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

But I'm hoping for something a touch more elegant?

+1  A: 

I guess it's not a bad solution for the problem. If you had an external stylesheet file, this piece of code will do the 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 could call it this way (script tags would be done by your server control):

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

This blog entry and the comments show some alternatives (ScriptManager.RegisterClientScriptBlock). But in my opinion your solution is okay.

splattne
+1  A: 

Here's another way... For example:

Parent ASPX portion:

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

Within 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, then you will need to merge the style with the control using the MergeStyle method. (This requires that the control be runat="server").

This code renders the following output: (Showing 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>
Cerebrus
Yeah... I'd found the CreateStyleRule but was really annoyed to see that it did not provide a way to provide an extra "styles" string setting. The style attributes I need are mostly not part of the Style() object.
Hmmm... quite right. I haven't found a way around that problem.
Cerebrus