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.

1

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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?

4 Comments

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.
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 <text>Yes, send me your 100 packet</text> inside the @if{} block.
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<MyEnum>(Model.PropertyThatStoresTheEnumValue);
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.