Is there a method to show string values instead of boolean values with EditorFor() in ASP.NET MVC?

Hadis Sulejmani 1 Reputation point
2021-11-03T13:43:44.443+00:00

I have a form where user needs to select the gender in a dropdown list, and I am using EditorFor() for this purpose, which is working well, but is displaying values as True and False, instead of Male, Female and Gender is a boolean property. How to convert boolean values into strings in this case. The code is as below:

<dl>
<dt>@azzedinehtmlsql .LabelFor(model => model.EmployeeInfo.Person.Gender</dt>
<dd>
@azzedinehtmlsql .EditorFor(model => model.EmployeeInfo.Person.Gender)
@azzedinehtmlsql .ValidationMessageFor(model => model.EmployeeInfo.Person.Gender)
</dd>
</dl>

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,246 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Michael Taylor 47,716 Reputation points
    2021-11-03T15:05:01.387+00:00

    If Gender is a boolean then what would you expect? If it isn't a boolean then that would be odd.

    EditorFor just looks at the top of the property and selects a default control (textbox in most cases). In your case if you want a dropdown then use DropDownList instead. If Gender is an enum then you tell it what enum to render (which sets the label and value) along with the value to bind against. Under the hood the select item that has a value that matches the value of the property is marked as selected when rendering and set when posting.

    1 person found this answer helpful.

  2. Yijing Sun-MSFT 7,061 Reputation points
    2021-11-04T03:00:00.87+00:00

    Hi @Hadis Sulejmani ,
    Why you don't use @azzedinehtmlsql .DropDownListFor? It's easy for drop downs.
    Just like this:

    @Html.DropDownListFor(m => m.StudentGender,   
                new SelectList(Enum.GetValues(typeof(Gender))),   
                "Select Gender")  
    
    public class Student  
    {  
        public int StudentId { get; set; }  
        public string StudentName { get; set; }  
        public Gender StudentGender { get; set; }  
    }  
      
    public enum Gender  
    {  
        Male,  
        Female      
    }  
    

    Do you just only want to use @azzedinehtmlsql .EditorFor?

    Best regards,
    Yijing Sun


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.