Home > Enterprise >  How to Display the name of a enum not the id in cshtml?
How to Display the name of a enum not the id in cshtml?

Time:11-02

I have a enum like this:

using System.ComponentModel;
using System;
using System.Collections.Generic;
namespace eVote.Data.Enums
{
    public enum Positions
    {
        CEO =1,
        ProductManager,
         CTO,
         SalesManager,
        FinanceManager,
         HR,
        Accountant


    }
}

When i use this enum in a AddAsync function i use like this:

 <div >
        <label asp-for="position">Function </label>
        <select asp-for="position"  asp-items="Html.GetEnumSelectList<Positions>()" asp-for="position"></select>
       
    </div>

But, when i go to index, the position displayed is the id of position

<td>@candidate.position</td>

Any thoughts?? enter image description here

CodePudding user response:

If you want to display the name of an enum value as a string, you have to call the ToString() method on the value.

enum UserRole {
   User,
   Admin
}

Console.WriteLine(UserRole.User.ToString());

This will print User.

CodePudding user response:

This is what I've done, added Display(Name... See also

public enum Positions
{
    [Display(Name = "CEO")]
    CEO,
    [Display(Name = "ProductManager")]
    ProductManager,
    [Display(Name = "CTO")]
     CTO,
     [Display(Name = "SalesManager")]
     SalesManager,
     [Display(Name = "FinanceManager")]
    FinanceManager,
    [Display(Name = "HR")]
     HR,
     [Display(Name = "Accountant")]
    Accountant
}
  • Related