0

Enum Class

public enum DataReleaseChoice 
{
    Accept, 
    Decline,
    [Display(Name = "Retrieve your application")]
    Continue
}

In my view:

<input name="@Html.NameFor(model => model.DataReleaseAuthorization)" type="submit" value="@DataReleaseChoice.Accept" class="btn btn-primary" />
<input name="@Html.NameFor(model => model.DataReleaseAuthorization)" type="submit" value="@DataReleaseChoice.Decline" class="btn btn-primary" />

All I am trying to do is to add a line for the new "Continue" button, but it should show the DisplayAttributes value ("Retrieve your application")

I've looked at the example provided at How to get the Display Name Attribute of an Enum member via MVC razor code? but am struggling to use it in the Razor view. I can display the value in the controller using the following code,

var displayAttribute = PAI.Web.Utilities.EnumHelper<DataReleaseChoice>.GetDisplayValue(DataReleaseChoice.Continue);

but when I use the same in the razor view as follows,

<input name="@Html.NameFor(model => model.DataReleaseAuthorization)" type="submit" value="@PAI.Web.Utilities.EnumHelper<DataReleaseChoice>.GetDisplayValue(DataReleaseChoice.Continue)" class="btn btn-primary" />, 

I get the error

Using the generic type 'EnumHelper<T>' requires 1 type arguments

I am using MVC 5.2.3, and have read in other forums that MVC 5 supports DisplayAttribute for Enums out of box.. I am struggling to use it though.

1 Answer 1

1

Use this extension method to get DisplayName for enum in Controller or View:

public static class EnumExtension
{
    public static string GetDisplayName(this Enum value)
    {
        var enumType = value.GetType();
        var enumName = Enum.GetName(enumType, value);
        var member = enumType.GetMember(enumName)[0];

        var attributes = member.GetCustomAttributes(typeof (DisplayAttribute), false);
        var outString = string.Empty;

        outString = ((DisplayAttribute) attributes[0]).ResourceType != null 
            ? ((DisplayAttribute) attributes[0]).GetName() 
            : ((DisplayAttribute)attributes[0]).Name;

        return outString;
    }
}

<input name="@Html.NameFor(model => model.DataReleaseAuthorization)" type="submit" value="@DataReleaseChoice.Continue.GetDsiplayName()" class="btn btn-primary" />,

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

Comments

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.