1

I have an element in a cshtml view and come code that generates a random color. No matter what I try I can't make it work. Using the @ symbol at all removes the highlighting of the color property (I assume this is an indicator that it's not going to work)

@using(//using code for accessing database)
 {
    //code to make query
    Random rnd = new Random();
    Color randomColor = Color.FromArgb(rnd.Next(256), rnd.Next(256), rnd.Next(256));
    //other code

    //displaying information
    <p style="color: @randomColor">@db.item</p>
}
Patrick D.
  • 11
  • 6

3 Answers3

0

You can't just stick a Color on the page. A Color is a struct. It's not a string.

You need to convert the Color to the appropriate HTML representation. See this question for some ideas on how to do that, such as:

public static String HexConverter(System.Drawing.Color c)
{
    return "#" + c.R.ToString("X2") + c.G.ToString("X2") + c.B.ToString("X2");
}

Once you have the string in a variable, you can output it into the view like any other string.

<p style="color: @HexConverter(randomColor)">@db.item</p>
John Wu
  • 50,556
  • 8
  • 44
  • 80
  • 1
    Actually there is a built in class ColorTranslator that can convert to hex code. ColorTranslator.ToHtml(Color). Checkout my answer. – kebin Jun 30 '17 at 23:18
0

First, calling color to string will return something like `Color [A=255, R=6, G=86, B=171]' so that will not work.

Instead you need to get the hex representation or use the RGB declaration

Now, assuming you are trying to output the p tag, when you are inside of a code block you can use @Html.Raw

 @Html.Raw("<p style='color: #" + randomColor.R.ToString("x2") + randomColor.G.ToString("x2") + randomColor.B.ToString("x2")  + "'>" + db.item + "</p>");

Using rgb you can do this:

@Html.Raw("<p style='color: rgb(" + randomColor.R + "," randomColor.G "," + randomColor.B +")'>" + db.item + "</p>");
Alexander Higgins
  • 6,765
  • 1
  • 23
  • 41
0

You need to convert the Color to actual hex code as follows:

<p style="color:@ColorTranslator.ToHtml(randomColor)">@db.item</p>
kebin
  • 163
  • 5