0

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 class="form-group">
        <label asp-for="position">Function </label>
        <select asp-for="position" class="form-control" 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

Yiyi You
  • 16,875
  • 1
  • 10
  • 22
Sergiu BRC
  • 17
  • 5

4 Answers4

0

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.

rotgers
  • 1,992
  • 1
  • 15
  • 25
0

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
}
Karen Payne
  • 4,341
  • 2
  • 14
  • 31
0

I test with following code,and it can work:

Model:

public class TestModel {
      
        public Positions position { get; set; }
    }
    public enum Positions
    {
        CEO = 1,
        ProductManager,
        CTO,
        SalesManager,
        FinanceManager,
        HR,
        Accountant


    }

action:

 public IActionResult B()
        {

            return View(new TestModel {  position=Positions.CEO });


        }

View:

@model TestModel 
<h1>@Model.position</h1>

result:

enter image description here

If it still doesn't work,try to check the type of position.

Yiyi You
  • 16,875
  • 1
  • 10
  • 22
0

You have to use the ToString() method to format it as a string.

<td>@candidate.position.ToString()</td>
rotgers
  • 1,992
  • 1
  • 15
  • 25
  • Not working. @candidate.position.ToString(). It s still show me the id – Sergiu BRC Nov 02 '22 at 10:50
  • Then what is the type of the variable `position`? If I have an enum `enum MyType { A, B, C }` and print a member of it `Console.WriteLine(MyType.A.ToString());` it prints `A`. – rotgers Nov 02 '22 at 11:05