3

I have a field in Model(tablaMetadata) with boolian field for gender as below: (I work with database first MVC)

 [DisplayName("gender")]
 [Display(Name = "gender")]
 public Nullable<bool> EmpSex { get; set; }

I want to get value from EmpSex as "Male" or "Female" by dropdownlist , then convert it to boolean (for posting form to database). I define Enum as below:

public enum gender
{
    Male=1,
    Female=0
}

I don't Know How can I use htmlhelper for Enumdropdownlist and convert string value of dropdownlist to boolean. Can you help me to define dropdownlist for Enum and converting values?

L Bar
  • 45
  • 7

1 Answers1

2

In your view you can create the dropdown like this

Create the list from enum like this

@{ 
    var genderList = Enum.GetValues(typeof(Gender)).OfType<Gender>().Select(m => new { Text = m.ToString(), Value = (int)m }).ToList(); 
}

and create the DropDown like this

@Html.DropDownList("EmpSex", new SelectList(genderList, "Value", "Text", Model.EmpSex))

or

@Html.DropDownListFor(model => model.EmpSex, new SelectList(genderList, "Value", "Text", Model.EmpSex))
Nitesh Kumar
  • 1,774
  • 4
  • 19
  • 26
  • it's Ok, but I want to set a css class for dropdownlist. I change your code in this form: @Html.DropDownListFor(model => model.Employees.EmpSex, new SelectList( genderList, "Value", "Text",new { @class = "form-control1 select2 ", style="width:100 %;" })). but class dosn't apply. is it correct? – L Bar Dec 12 '17 at 14:33
  • SO, you can add CSS by adding one more parameter in DropDownList `, new { @class = "yourCSS" }` – Nitesh Kumar Dec 12 '17 at 14:36
  • the correct code is `@Html.DropDownListFor(model => model.EmpSex, new SelectList(genderList, "Value", "Text", "----"), new { @class = "yourCSS" })` – Nitesh Kumar Dec 12 '17 at 14:37
  • I use these commands of Enum for "int" field in sql and it was correct, but I use it for " bit " field in sql and I encounter to validation error message. can you tell me which property must be changed? I can't change " int" to " bit". – L Bar Dec 14 '17 at 15:00
  • You can try changing the definition of enum like `public enum gender : byte`. – Nitesh Kumar Dec 14 '17 at 15:09
  • I change it but the error is still remains.the message is "the value 0 is not valid for gender". – L Bar Dec 14 '17 at 19:40