سؤال

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?

هل كانت مفيدة؟

المحلول

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()".

نصائح أخرى

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top