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?

1 Answer 1

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))
Sign up to request clarification or add additional context in comments.

6 Comments

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?
SO, you can add CSS by adding one more parameter in DropDownList , new { @class = "yourCSS" }
the correct code is @Html.DropDownListFor(model => model.EmpSex, new SelectList(genderList, "Value", "Text", "----"), new { @class = "yourCSS" })
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".
You can try changing the definition of enum like public enum gender : byte.
|

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.