Search code examples
c#asp.net-coremodel-view-controllerrazorenums

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


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


Solution

  • 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.