Storing String Versions of Database State Values

advertisements

I'm writing an ASP.NET MVC 3 site and I need to convert some integer values from the database that represent statuses with user readable strings, for example:

...
<td>
@item.Status
</td>
...

I've written an HTML Helper to do the conversion:

    public static string MessageType(this HtmlHelper helper, int type)
    {
        string messageType = "Unknown";
        switch((Types.MessageTypes)type)
        {
            case Types.MessageTypes.Join:
                messageType = "Join App";
                break;
            case Types.MessageTypes.New:
                messageType = "New App";
                break;
        }

        return messageType;
    }

And I'm storing the types as an enumeration in the Types class.

My question is whether there is a cleaner way to do this? I don't like these magic strings in my code and it creates numerous dependencies in different parts of the code.

Any thoughts?

Many thanks, Sam


I usual decorate the enums with the DisplayAttribute like this.

    enum MessageTypes
    {
       [Display(Name = "Join App")]
       Join,
       [Display(Name = "New App")]
       New
    }

Then I use a helper to extract them:

    public static string EnumDisplay(this HtmlHelper helper, Enum model)
    {
        var enumType = model.GetType();
        var modelValue = Convert.ToInt64(model);

        var matches = from field in enumType.GetMembers()
                      where field.MemberType == MemberTypes.Field && Enum.IsDefined(enumType, field.Name)
                      let value = Convert.ToInt64(Enum.Parse(enumType, field.Name, false))
                      where modelValue == value
                      let attribute = field.GetCustomAttributes(typeof (DisplayAttribute), false).Cast<DisplayAttribute>().FirstOrDefault()
                      select attribute == null
                          ? field.Name
                          : attribute.Name;

        return matches.FirstOrDefault() ?? "Unknown";
    }

Then you can do

  @Html.EnumDisplay((MessageType)item.MessageType)