How find the enum name for corresponding value and use it in DisplayFor?

I need to display the name of the enum for corresponding value inside DisplayFor HtmlHelper. I have the following enum:

public enum CheckStatus
    {
        Yes = 1,
        No = 2,
        Maybe =3
    }

I’m displaying values for a model normally like this:

@Html.DisplayFor(modelItem => item.Name)

The problem is that at one point I have this:

@Html.DisplayFor(modelItem => item.Status)

That line displays only status value which is set before from enum (1,2 or 3). Instead of that I need somehow to display name for that value. So, if status code is 2, I want to display ‘No’, not number 2.

I had the similar problem with getting enum names when I was populating dropdown list and I managed to solve it like this:

@Html.DropDownListFor(model => model.Item.Status,
                new SelectList(Enum.GetValues(typeof(Pro.Web.Models.Enums.CheckStatus))))

I am a little bit lost in how to get only that one name from the value of the enum.

Thank you for your help.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

It’s not very clear from your question what’s the underlying type of the Status property. If it is CheckStatus, then @Html.DisplayFor(modelItem => item.Status) will display exactly what you expect. If on the other hand it is an integer you could write a custom helper to display the proper value:

public static class HtmlExtensions
{
    public static IHtmlString DisplayEnumFor<TModel>(this HtmlHelper<TModel> html, Expression<Func<TModel, int>> ex, Type enumType)
    {
        var value = (int)ModelMetadata.FromLambdaExpression(ex, html.ViewData).Model;
        string enumValue = Enum.GetName(enumType, value);
        return new HtmlString(html.Encode(enumValue));
    }
}

and then use it like this:

@Html.DisplayEnumFor(modelItem => item.Status, typeof(CheckStatus))

and let’s suppose that you wanted to bring this helper a step further and take into account the DisplayName attribute on your enum type:

public enum CheckStatus
{
    [Display(Name = "oh yeah")]
    Yes = 1,
    [Display(Name = "no, no, no...")]
    No = 2,
    [Display(Name = "well, dunno")]
    Maybe = 3
}

Here’s how you could extend our custom helper:

public static class HtmlExtensions
{
    public static IHtmlString DisplayEnumFor<TModel>(this HtmlHelper<TModel> html, Expression<Func<TModel, int>> ex, Type enumType)
    {
        var value = (int)ModelMetadata.FromLambdaExpression(ex, html.ViewData).Model;
        string enumValue = Enum.GetName(enumType, value);
        var field = enumType.GetField(enumValue);
        if (field != null)
        {
            var displayAttribute = field
                .GetCustomAttributes(typeof(DisplayAttribute), false)
                .Cast<DisplayAttribute>()
                .FirstOrDefault();
            if (displayAttribute != null)
            {
                return new HtmlString(html.Encode(displayAttribute.Name));
            }
        }
        return new HtmlString(html.Encode(enumValue));
    }
}

Method 2

Edit:

You can simply try this way. please try my below code in your controller class

controller:

int enumvalue=(int)(YourModel.Status)// this property must be integer value only
var checkStatusName= Enum.GetName(typeof(CheckStatus), enumvalue);

Method 3

Adapted @DarinDimitrov code as display template.

If you have

public enum CheckStatus
{
    [Display(Name = "oh yeah")]
    Yes = 1,
    [Display(Name = "no, no, no...")]
    No = 2,
    [Display(Name = "well, dunno")]
    Maybe = 3
}

public class MyModel
{
    public CheckStatus Status { get; set; }
}

put following into Views/DisplayTemplates/Enum.cshtml :

@using System.ComponentModel.DataAnnotations
@model object

@{
    var value = Model.ToString();
    var field = Model.GetType().GetField(value);
    if (field != null)
    {
        var displayAttribute = field
                .GetCustomAttributes(typeof(DisplayAttribute), false)
                .Cast<DisplayAttribute>()
                .FirstOrDefault();

        if (displayAttribute != null)
        {
            value = displayAttribute.GetName();
        }
    }
}

@value

and now you can simply write in your view:

@Html.DisplayFor(model => model.Status)

Method 4

using razor/MVC you can get this for “free” if your property in not declared as an int type but rather as the enum type yoou are using.

The problem I have with Darin solution is although it works for me if I use the int type, I could not get the look of my other fields @Html.EditorFor(…) in the view.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x