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

大憨熊 提交于 2019-11-29 18:21:58

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!