1

I want to list an enum in my Razor DropDownList. My model's property is :

public gender gender { get; set; }

Here is my view code :

@Html.DropDownListFor(model => model.gender, new SelectList(Enum.GetValues(typeof(gender))),new { @class="form-control"})

The list works but the jQuery Validation error message is The field Gender must be a number.

How can I solve it ?

Thanks

3 Answers 3

4

This is how you can achieve with **Enum** :

Model :

 public enum Genders
 {
            [Display(Name = "Male")]
            M = 1,
            [Display(Name = "Female")]
            N = 2            
 }
 public Genders Gender { get; set; } 

View :

@Html.EnumDropDownListFor(x => x.Gender, "Please Select", new { @class = "form-control" })
Sign up to request clarification or add additional context in comments.

7 Comments

Enum achieve in ef designer (edmx) enum types
what if you put below code in your .cshtml instead your code. @Html.EnumDropDownListFor(x => x.Gender, "Please Select", new { @class = "form-control" }) What error you have got ? Is it working or not ?
Not working error message Return type 'System.Int32' is not supported.
Can you post the values of Enum gender ??
doesnt post value
|
2

Try this

Model

public int gender { get; set; }

Controller

public enum selectgender{
...
}

ViewBag.selectgender= Enum.GetValues(typeof(selectgender)).Cast<selectgender>();

View

@Html.DropDownListFor(model => model.gender, new SelectList(ViewBag.selectgender), "Select Gender",new { @class = "form-control" })

Comments

2

Update 2020...

Add an enum type, gender, to the model.

public enum GenderType
{
    Male,
    Female,
    Other
}
public GenderType Gender { get; set; }

In view, do this...

<select asp-for="Gender" asp-items="@Html.GetEnumSelectList<GenderType>()">

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.