4

I have a WebGrid that displays a Status enum in one column. There are a couple of enum members that consist of two words and I want to use the enum's DisplayName property rather than the default ToString() representation, e.g. "OnHold" should be displayed as "On Hold".

@grid.GetHtml(
    tableStyle: "webGrid",
    headerStyle: "header",
    alternatingRowStyle: "alt",
    mode: WebGridPagerModes.All,
    columns: grid.Columns(
        grid.Column("JobId", "Job ID"),
        grid.Column("Status", "Status", item =>
        {
            return ModelMetadata
                       .FromLambdaExpression(**What goes in here**)
                       .DisplayName;
        }),
        grid.Column("OutageType", "Outage Type"),

Is there some way I can get this information using the model metadata?

tereško
  • 58,060
  • 25
  • 98
  • 150
David Clarke
  • 12,888
  • 9
  • 86
  • 116

2 Answers2

3

We had the same problem. I ended up solving it by making the following HtmlHelper extension:

    public static MvcHtmlString DisplayName(this HtmlHelper html, object value)
    {
        var displayAttributes = (DisplayAttribute[])value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof(DisplayAttribute), false);
        if (displayAttributes == null || displayAttributes.Length == 0)
        {
            return new MvcHtmlString(value.ToString());
        }
        return new MvcHtmlString(displayAttributes[0].Name);
    }

The column could then be made like:

    grid.Column("Status", "Status", item => Html.DisplayName(item.Status)),

Edit: For globalization, change "displayAttributes[0].Name" to "displayAttributes[0].GetName()".

superguppie
  • 106
  • 7
0

I don't have VS in front of me, but maybe you could try this...

[TypeConverter(typeof(PascalCaseWordSplittingEnumConverter))]

Check out this article for how it can be used in a dropdown list.

Chris Noffke
  • 317
  • 1
  • 7
  • Thanks Chris, I'm currently using a regular expression to add a space before capitals but it's a hack and knowing the information is available in the attribute I would prefer to use that instead. – David Clarke Mar 14 '14 at 08:34