如何为此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)
答案 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)