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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With