使用dropdownlistfor为具有list属性的模型

时间:2015-06-11 14:07:21

标签: c# asp.net-mvc asp.net-mvc-4 model

如何为此viewmodel使用dropdownlistfor?

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

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

我该怎么做?

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

1 个答案:

答案 0 :(得分:1)

您可以将选定的ID放入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;}
}

在控制器中:

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");

在视图中:

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