MVC5中数据库的下拉列表

时间:2016-12-21 13:53:17

标签: c# asp.net-mvc html.dropdownlistfor

视图模型:

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来解决这个问题,但使用它们不是不是最理想的吗?那么使用带有数据库数据的模型类获取下拉列表的最佳方法是什么?

1 个答案:

答案 0 :(得分:3)

首先你需要在viewModel中添加一个SelectList:

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>