Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 615
user53794 Avatar asked Feb 25 '09 07:02

user53794


1 Answers

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.

like image 88
splattne Avatar answered Oct 20 '22 14:10

splattne