使用MVC基于Enum值定义HTML元素颜色

时间:2016-08-02 13:42:10

标签: c# css asp.net-mvc enums

我的MVC项目中有一个问题类别枚举:

public enum QuestionCategory
{
    [Display(Name = "Enum_Category_Overall_Display", ResourceType = typeof(ResQuestion))]
    Overall = 0,
    [Display(Name = "Enum_Category_Service_Display", ResourceType = typeof(ResQuestion))]
    Service = 1,
    [Display(Name = "Enum_Category_Facilities_Display", ResourceType = typeof(ResQuestion))]
    Facilities = 2,
    [Display(Name = "Enum_Category_Team_Display", ResourceType = typeof(ResQuestion))]
    Team = 3
}

我需要根据枚举值在视图中设置图表颜色。

现在我在视图中进行切换:

string color = "";
switch (answer.QuestionCategory)
{
    case Core.Data.Models.QuestionCategory.Overall: color = "#10c469"; break;
    case Core.Data.Models.QuestionCategory.Service: color = "#f9c851"; break;
    case Core.Data.Models.QuestionCategory.Facilities: color = "#188ae2"; break;
    case Core.Data.Models.QuestionCategory.Team: color = "#5b69bc"; break;
}

我在图表中应用颜色:

<round-progress max="5" current="@answer.Numeric" color="@color" semi="isSemi" rounded="rounded" clockwise="clockwise" responsive="responsive"></round-progress>

问题是我在另一个视图中需要基于Enum值的颜色,我不想重复代码(DRY)。

2 个答案:

答案 0 :(得分:2)

创建HtmlHelper扩展程序:

public static class HtmlHelperExtensions
{
    public static MvcHtmlString QuestionCategoryColor(this HtmlHelper helper, QuestionCategory category)
    {
        string color = "";
        switch (category)
        {
            case Core.Data.Models.QuestionCategory.Overall: color = "#10c469"; break;
            case Core.Data.Models.QuestionCategory.Service: color = "#f9c851"; break;
            case Core.Data.Models.QuestionCategory.Facilities: color = "#188ae2"; break;
            case Core.Data.Models.QuestionCategory.Team: color = "#5b69bc"; break;
         }

        return MvcHtmlString.Create(color);
    }
}

然后在您的观看中使用@Html.QuestionCategoryColor(...)

答案 1 :(得分:2)

您可以创建一个html帮助器作为他的答案中提到的mxmissle。另一种选择是在枚举上创建一个扩展方法。

public static class QuestionCategoryExtensions
{
    public static string ToColor(this QuestionCategory category)
    {
            switch (category)
            {
                case QuestionCategory.Overall: return  "#10c469"; 
                case QuestionCategory.Service: return "#f9c851";
                case QuestionCategory.Facilities: return "#188ae2"; 
                case QuestionCategory.Team: return "#5b69bc"; 
            }
            return string.Empty;
        }
    }
}

在您的视图中,您只需在模型的枚举属性上调用它即可。

假设您的视图模型具有名为Cat enter code here类型的属性,类型为QuestionCategory enum

你可以这样做

@Model.Category.ToColor()

此扩展方法可用于视图和控制器代码。