Reputation: 2828
I asked a question about this already, but I wrong-phrased it.
I have a method GetRandColor()
on the server that returns a System.Drawing.Color
object.
What I want is to be able to set html attributes using this when the page loads. So as an example,
<html>
<body bgcolor="#GetRandColor()">
<h1>Hello world!</h1>
</body>
</html>
Upvotes: 9
Views: 19097
Reputation: 17194
You can do that with the help of inline expression: Inline expressions in the .NET Framework
Displaying expression (<%= ... %>)
bgcolor="<%= System.Drawing.ColorTranslator.ToHtml(GetRandColor()) %>"
Upvotes: 2
Reputation: 1063
You can use ColorTranslator to convert Drawing.Color to HTML color value. For example,
System.Drawing.Color c = System.Drawing.ColorTranslator.FromHtml("#F5F7F8");
String strHtmlColor = System.Drawing.ColorTranslator.ToHtml(c);
This link will help you too : msdn.microsoft.com/en-us/library/system.drawing.colortranslator.fromhtml.aspx
Upvotes: 1
Reputation: 63970
You can't return a System.Drawing.Color
object from your function because browsers only understand text. So instead, you should return the string representation of the color, be in RGB, HEX format or what have you.
Your method then should look like this:
protected string GetRandColor()
{
return ColorTranslator.ToHtml(Color.Red);
}
And you can set the background of your form as so:
<body style="background-color:<%=GetRandColor()%>;">
Upvotes: 23
Reputation: 101778
If GetRandColor() is in a static class, this should work:
<body bgcolor="<%= System.Drawing.ColorTranslator.ToHtml(ClassName.GetRandColor()) %>">
You may need to add the class' namespacess before the class name.
Upvotes: 2
Reputation: 37466
public string GetRandHtmlColor(){
System.Drawing.Color c = GetRandColor();
return System.Drawing.ColorTranslator.ToHtml(c);
}
Upvotes: 0