Search code examples
c#-4.0model-view-controllerenumsdata-annotationsdisplay-templates

Displaying html-formatted text for enum values in MVC


I have an MVC 5 app that uses an existing system's values to display unit-related data. I'm utilizing data annotations to convert the nasty-looking legacy data to nicely-formatted versions on the UI.

I'm trying to figure out how to display the M3 value nicely, using a superscript for the number "3". How would you go about fixing this?

public enum UnitTypes
{
    [Display(Name = "kg")]
    KG,
    [Display(Name = "kl")]
    KL,
    [Display(Name = "m<sup>3</sup>")]
    M3,
}

This DisplayTemplate uses the display attribute, if it exists. Otherwise it defaults to the name of the enum.

@using System.ComponentModel.DataAnnotations

@{
    var type = (Type)Model.GetType();
    var field = type.GetField(Model.ToString());
    if (field != null)
    {
        var display = ((DisplayAttribute[])field.GetCustomAttributes(typeof(DisplayAttribute), false)).FirstOrDefault();
        if (display != null)
        {
            @display.GetName()
        }
        else
        {
            @Model
        }
    }
}

Solution

  • I found an easy answer. I just had to use a unicode value to accomplish this.