James
James

Reputation: 1392

Dropdownlist using MVC and Razor

I have search for days to find and figure out a multi-directional dropdownlist answer to this question.

I have the following model

public class Person()
{
   public int Id { get; set; }
   public string Name { get; set; }
   public Gender Gender { get; set; }
}

I have tried to make Gender as an enum, string, SelectListItem....(the list goes on!)

In my HTTPGET person razor view I want add a new Person, with a dropdown generated with a list of genders ( male, female....)

and when the user submits the form it would pass the Person to the HTTPPOST Person view with the updated Gender attached.

I don't mind what type Gender is, just as long as it can post between controller and view both ways.

kind regards

Upvotes: 1

Views: 538

Answers (1)

christofr
christofr

Reputation: 2700

This is definitely possible with the standard @Html.DropDownListFor(...) helper.

However, when creating your view, you need to convert your Enum to an IEnumerable<SelectListItem> for it to work. See this answer for an example of a helper method to convert an Enum to the correct type.

When you have this hepler method in your code, you can do something like:

Html.DropDownListFor(m => m.Gender , ListExtensions.ToSelectList(Model.Gender, m => m.Gender))

Upvotes: 2

Related Questions