1

I'm trying to work out a best practice for building drop down boxes for values that need to bind to values in a database.

Currently I am about to use the 3rd answer from this list How do you create a dropdownlist from an enum in ASP.NET MVC?

But then I was thinking if I bind strongly against the Enum, and then want to change the order of the items, or add new items, I'll need to make sure the order of the enum isn't actually the value being stored in the db, and have to have a binding layer of some kind.

Does anyone have the definitive way to work with drop down lists that relate to a db?

Community
  • 1
  • 1
Chris Barry
  • 4,564
  • 7
  • 54
  • 89
  • side note - if you want to link to a specific answer, click the "link" button under it to permalink to it – RPM1984 Feb 14 '12 at 02:02

3 Answers3

1

Personally I avoid using enums in my view models. They don't play well with ASP.NET MVC. So if I need to render a dropdown list in one of my views I define 2 properties on my corresponding view model:

public class MyViewModel
{
    public string SelectedValue { get; set; }
    public IEnumerable<SelectListItem> Values { get; set; }
}

that are populated in my controller action from the database and in the view:

@Html.DropDownListFor(x => x.SelectedValue, Model.Values)
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
0

Have a strongly typed view model for the list with a partial view to match. Have an action in a controller which fills the view model and then returns it to the view. Wherever you want to use the dropdown, insert the partial view in your view.

Travis J
  • 81,153
  • 41
  • 202
  • 273
0

I'm a fan of using an extension method for this task:

public static List<SelectListItem> ToSelectList<T>( this IEnumerable<T> enumerable, Func<T, string> value, Func<T, string> text, string defaultOption)
{
    var items = enumerable.Select(f => new SelectListItem()
                                          {
                                              Text = text(f) ,
                                              Value = value(f)
                                          }).ToList();

    if (!string.IsNullOrEmpty(defaultOption))
    {
                    items.Insert(0, new SelectListItem()
                        {
                            Text = defaultOption,
                            Value = "-1"
                        });
    }

    return items;
}

Within your controller you select the data that you wan't to represent as items within a drop down. Note, in this example I'm selecting cities from the db:

    SomeModel.City =
        (from l in _locationRepository.GetAll() select new  { l.Area.AreaDescription })
            .Distinct()
            .ToSelectList(x => x.AreaDescription, x => x.AreaDescription, "All");

And the actual drop down within the view:

@Html.DropDownList("City", Model.City)
Jesse
  • 8,223
  • 6
  • 49
  • 81