How find the enum name for corresponding value and use it in DisplayFor?
asp.net, asp.net-mvc, asp.net-mvc-4, enums, razor
Solution
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));
}
}
Problem
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.