使用javascript评估/更改Gridview中的显示值

时间:2012-09-21 14:10:36

标签: javascript asp.net data-binding gridview binding

使用javascript,在asp.net网格视图中将显示的boolen值切换为字符串,如下所示

<asp:Label ID="Correct" Text='<%# Eval("Correct").ToString().Equals("true") ? " Correct " : " Wrong " %>'  runat="server"/></td>

如果数据类型是int&amp;是否有任何方法可以切换3个不同的值值是1,2&amp; 3分别显示低,中,低高。我尝试了如下,但它没有工作

<asp:Label ID="Difficulty" Text='<%# Eval("Difficulty").ToString().Equals("1") ? " low" : (("Difficulty").ToString().Equals("2") ? " medium " : " high ") %>'  runat="server"/></td>

1 个答案:

答案 0 :(得分:1)

即使可以使用三元运算符完成 - 也很难阅读。我想说你最好的选择是在类后面的相应代码中定义一个函数:

protected string GetDifficultyText(object difficultyObj)
{
    string difficultyId = difficultyObj as string;

    if (string.IsNullOrWhiteSpace(difficultyId))
    {
        return string.Empty; //or throw exception
    }

    switch (difficultyId)
    {
        case "1":
            return " low";
        case "2":
            return " medium";
        case "3":
            return " high";
        default:
            return string.Empty; //or throw exception
    }
}

然后在标记中调用它:

<asp:Label ID="Difficulty"
           Text='<%# GetDifficultyText(Eval("Difficulty")) %>'
           runat="server"/>