2

I have an enum OType as:

public enum OType
    {
        First_enum_option,
        Second_enum_option,
        None_of_the_above
    }

My model has an enum field EType of this type, which is displayed in the view as:

@Html.DisplayFor(x => x.EType)

In the view, the option is displayed correctly. But I want to replace underscores with spaces. With normal strings, I usually do this with Replace("_", " ")

If I use: @Html.DisplayFor(x => x.EType.ToString().Replace("_", " ")), I get this System.InvalidOperationException with message:

Templates can be used only with field access, property access, single-dimension >array index, or single-parameter custom indexer expressions.

I have thought of this solution:

<td>
    @{ 
         string str = item.EType.ToString().Replace("_", " ");
     }

    @str
</td>

This solves the problem. Is there any concise and elegant way to achieve this?

Vivekanand P V
  • 861
  • 3
  • 13
  • 27
  • 4
    Add a `[Display]` attribute to each value and then use extension methods as described in [these answers](http://stackoverflow.com/questions/13099834/how-to-get-the-display-name-attribute-of-an-enum-member-via-mvc-razor-code) and in the view use `@Model.EType.GetDisplayValue()` –  Mar 15 '16 at 04:04
  • Possible duplicate of [How to make a default editor template for enums in MVC 4?](http://stackoverflow.com/questions/19139326/how-to-make-a-default-editor-template-for-enums-in-mvc-4) – NightOwl888 Mar 15 '16 at 04:17

2 Answers2

1

Change your enums to:

public enum OType
    {
        [Display(Name = "First enum option")]
        First_enum_option,

        [Display(Name = "Second enum option")]
        Second_enum_option,

        [Display(Name = "None of the above")]
        None_of_the_above
    }

and use,

@Model.EType.GetDisplayValue()

in your view.

1

Use:

@Html.DisplayFor(x => x.EType).ToString().Replace("_", " ")
Pismotality
  • 2,149
  • 7
  • 24
  • 30