I Can't get a DropDownList to populate from table. EF and MVC4

前端 未结 1 733
慢半拍i
慢半拍i 2020-12-22 14:00

I believe this will create a list in my HomeController. But not sure what calls it or where it goes in the Controller beside maybe the first Add ActionResult (GET method).

相关标签:
1条回答
  • 2020-12-22 14:21

    You need to pass the SelectList to your view. Ideally your view model should include a property for the SelectList but you can (yuk) use ViewBag, for example

    View Model

    public class MyViewModel
    {
      public int SponsorID { get; set; }
      // other properties
      public SelectList SponsorList { get; set; }
    }
    

    Controller

    public ActionResult SomeThing()
    {
      MyViewModel model = new MyViewModel();
      // assign the select list
      var sponsors = from s in db.tblSponsors;
      model.SponsorList = new SelecList(sponsors, "SponsorID", "BizName");
      return View(model);
    }
    

    View

    @Html.DropDownListFor(model => model.SponsorID, Model.SponsorList);
    

    or if you assigned the select list to ViewBag

    @Html.DropDownListFor(model => model.SponsorID, (SelectList)ViewBag.SponsorList);
    
    0 讨论(0)
提交回复
热议问题