Get Enum DisplayName in WebGrid

I have a WebGrid that displays an enumeration of state in a single column. There are several members of an enumeration that consist of two words, and I want to use the enum property DisplayNamerather than the default view ToString(), for example. "OnHold" should display 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 any way to get this information using model metadata?

+4
source share
2 answers

We had the same problem. I decided to solve this by running 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);
    }

Then the column can be made as follows:

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

: "displayAttributes [0].Name" to "displayAttributes [0].GetName()".

+3

VS , , , ...

[TypeConverter(typeof(PascalCaseWordSplittingEnumConverter))]

, .

0

Source: https://habr.com/ru/post/1531695/


All Articles