1

I'm trying to dynamically populate a table in my ASP.NET webpage from an Azure Storage Table and one of the features I wanted to include is to change the color of the text depending on the value of the element.

I'm using a DataList object which is calling a GetEntries() method to get a list of all the objects to display.

The text in each cell of the table is dynamically displayed using:

<%# Eval("VariableName") %> 

So I tried changing the color of the text by doing something like this for each object in the GetEntries() method:

if (condition) 
   VariableName = "<font color=\"red\">" + VariableName + "</font>";
else
   // ...

When I run my program, the text is still black and when I view source, the <font color="red">Bob</font is only Bob.

Does the HTML get stripped when using Eval?

If so, is there an efficient way to change the text color based on the values?

Thanks!

4

1 回答 1

2

To render as html you can try this:

<asp:Literal Text='<%# Eval("VariableName") %>' Mode="PassThrough" runat="server" />

This requires that you have html (with color info) in VariableName, which may not be pretty.

Alternative 1:

But it will be better if you can add a public property say VariableColor (and leave VariableName unchanged):

public Color VariableColor
{
    get
    {
        return <condition>? Color.Red : Color.Empty;
    }
}

and use it like this:

<asp:Label Text='<%# Eval("VariableName") %>' ForeColor='<%# Eval("VariableColor") %>' runat="Server" />

Alternative 2:

Even better could be to create a public bool property (say IsDangerous) which evaluates the condition:

public bool IsDangerous
{
    get
    {
        return <condition>;
    }
}

and use it like this:

<asp:Label Text='<%# Eval("VariableName") %>' ForeColor='<%# ((bool)Eval("IsDangerous"))?Color.Red:Color.Empty %>' runat="Server" />
于 2013-07-03T01:11:02.880 回答