Patrick Patrick - 1 year ago 70
CSS Question

Define HTML element color based on a Enum value with MVC

I have a question category enum in my MVC project:

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

And I need to set a chart color in the View based on the value of the Enum.

Now I do a switch in the View:

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;

And I apply the color in the chart:

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

The problem is that I need the color based on the Enum's value in another View and I don't want to repeat the code (DRY).

Answer Source

You can create an html helper as mxmissle mentioned in his answer. Another option is to create an extension method on the enum.

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;

and in your view, you can simply call this on the enum property of your model.

Assuming your view model has a property called Catenter code hereegory of type QuestionCategory enum

you can do like


This extension method can be used in both views and controller code.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download