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

你。 提交于 2019-12-18 09:58:48

问题


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).

    public static IEnumerable<SelectListItem> items()
    {

        using (oesacEntities_compact db = new oesacEntities_compact())
        {
            var query = from s in db.tblSponsors select new { s.SponsorID, s.BizName };

            return query.AsEnumerable()
                .Select(x => new SelectListItem
                {
                    Value=x.SponsorID.ToString(),
                    Text = x.BizName
                }).ToList();
        }

    }

I can't seem to send it to the Add view or to reference it from the Add view:

<div class="editor=field">
    @Html.DropDownListFor(model => model.SponsorID,IEnumerable<SelectListItem> SelectList);   
</div>

It seems so simple in other coding languages. I want to populate a pulldown with about 200 sponsor ID's for value, BizNames for text. For now at least. God help me after that when I want to show an Edit view with the value selected. thankyou stackoverflow


回答1:


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);


来源:https://stackoverflow.com/questions/25676914/i-cant-get-a-dropdownlist-to-populate-from-table-ef-and-mvc4

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