MVC5 中数据库的下拉列表

Dropdownlist from database in MVC5

ViewModel:

public class GroepModel
    {
        public int id { get; set; }
        public String Naam { get; set; }
        public String Beschrijving { get; set; }
    }

控制器:

public class GroepController : Controller
{
    AlinaDatabaseDataContext db = new AlinaDatabaseDataContext();
    // GET: Groep
    public ActionResult Groepen()
    {
        List<GroepModel> groepen = Mapper.Map<List<GroepenWerkvorm>, List<GroepModel>>(db.GroepenWerkvorms.ToList());

        return View(groepen);
    }
}

查看

@model alina1617.Models.GroepModel

@{
    ViewBag.Title = "Groepen";
}

<h2>Groepen</h2>
<div>
    @Html.DropDownListFor(model => model. //This is not working  )
</div>

我环顾四周,发现很多东西都可以使用 ViewBags 解决这个问题,但使用它们不是最理想的吗?那么,使用模型 class 和数据库中的数据获取下拉列表的最佳方法是什么?

首先您需要将 SelectList 添加到您的 viewModel 中:

public class MyViewModel {
   public SelectList list {get;set;}
   public int selectedItem {get;set;}
}

然后您需要将您的列表添加到 SelectList 中:

public class GroepController : Controller
{
    AlinaDatabaseDataContext db = new AlinaDatabaseDataContext();
    // GET: Groep
    public ActionResult Groepen()
    {
        List<GroepModel> groepen = Mapper.Map<List<GroepenWerkvorm>,     List<GroepModel>>(db.GroepenWerkvorms.ToList());

        var model = new MyViewModel();

        model.list = new SelectList(groepen, "id", "Naam");

        return View(model);
    }
}

并在视图中:

@model alina1617.Models.MyViewModel

@{
    ViewBag.Title = "Groepen";
}

<h2>Groepen</h2>
<div>
    @Html.DropDownListFor(model => model.selectedItem, Model.list  )
</div>