2

I am trying to retrieve the [Display] text below for whichever enum is saved in the database (i.e., if None, then corresponding is "No thanks.") without having to code an @if block in my view. I guess it's not possible, but thought I would ask.

public enum MyEnum
{
    [Display(Name = "No thanks.")]
    None,
    [Display(Name = "Yes, send me your 100 Packet.")]
    100Packet,
    [Display(Name = "Yes, send me your 200 Packet.")]
    200Packet
}

Right now, the only solution I have is to do this in my view:

@Model.MyEnumRadioButton // displays saved item in DB (i.e., "100Packet")

@if (Model.MyEnumRadioButton == MyEnum.None)
{
    <text>No thanks.</text>
}
....

and repeat that for each item in the enum. For this small example it's no big deal, but I have a lot of different enum's, some with up to 10 choices.

For example, is there something I can do with the @Model.MyEnumRadioButton to make it display the text?

Any thoughts? Thanks in advance.

REMESQ
  • 1,190
  • 2
  • 26
  • 60

2 Answers2

2

I found a simple answer to my problem:

MVC.net get enum display name in view without having to refer to enum type in view

All I have to do is @MyEnum.100Packet.DisplayName()

Community
  • 1
  • 1
REMESQ
  • 1,190
  • 2
  • 26
  • 60
1

See this post, he is using a description attribute to achieve what you are after I believe:

How do I have an enum bound combobox with custom string formatting for enum values?

Community
  • 1
  • 1
Rick Petersen
  • 734
  • 5
  • 15
  • I think he's trying to display those values when the combo-box is generated. In my scenario I can do that no problem. What I am after is a view that is calling up what has been saved in the database. The `enum` value is stored in the DB, and I want to populate my view with the text stored in the attribute, not the `enum`. – REMESQ Nov 19 '12 at 21:55
  • I thought something like `MyEnum.100Packet.ToString();` might work in the view. Something to shortcut having to do an `@if` statement and then writing out `Yes, send me your 100 packet` inside the `@if{}` block. – REMESQ Nov 19 '12 at 21:57
  • I don't think I understand your problem with the link. He was trying to use it in a combobox and failing, but I think what he was doing would work for you. You have a view, bound to a model. On that model, you have a property that stores a value that matches one of the values in the enum. In that case, using the example from that link, you should just be able to do: `GetDescription(Model.PropertyThatStoresTheEnumValue);` – Rick Petersen Nov 19 '12 at 22:23
  • Not that it was a bad example, just overly complex for my scenario (which I admit I didn't explain well). My answer contains quicker solution. – REMESQ Nov 19 '12 at 23:19