Using dropdownlistfor for model with list property

1.7k Views Asked by At

How do I use dropdownlistfor for this viewmodel?

public class ViewModel
{
    public IEnumerable<Model1> model1{ get; set; }
}

    public class Model1
{
    public string Name { get; set; }
    public int Id{ get; set; }
}

How should I do this?

@model Models.ViewModels.ViewModel
@Html.DropDownListFor(model => model.model1)
1

There are 1 best solutions below

6
On BEST ANSWER

You can put the selected id into your viewmodel.

public class ViewModel
{
    public IEnumerable<SelectListItem> Model1Items{ get; set; }
    public int SelectedId { get; set; }
}
public class Model1{
    public int Id {get; set;}
    public string Name {get; set;}
}

In the Controller:

var items = (from m in db.Model1s
             select new SelectListItem{
                 Value = m.Id,
                 Text = m.Name
             }); // This is where you bind your Model1 to the dropdownlist

// Add a default id-name pair as needed.
YourViewModel.Model1Items = new SelectList(items.ToList(), "Value", "Text");

In the view:

@Html.DropDownListFor(model => model.SelectedId, Model.Model1Items)