我不能让一个DropDownList从表填充。 EF和MVC4 [英] I Can't get a DropDownList to populate from table. EF and MVC4
问题描述
我相信这将创建一个在我的HomeController列表。但不知道什么叫它或者它会在旁边控制器也许是第一个加入的ActionResult(GET方法)。
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>
这似乎在其他的编码语言那么简单。我想填充下拉约200赞助商的ID为价值,BizNames文本。至少现在。上帝帮助我之后,当我想显示与选定值的编辑视图。
三江源计算器
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
推荐答案
您需要将的SelectList
传递给你的视图。理想的情况是你的视图模型应该包括一个属性的SelectList
,但你可以(议员)使用ViewBag,例如:
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
查看型号
public class MyViewModel
{
public int SponsorID { get; set; }
// other properties
public SelectList SponsorList { get; set; }
}
控制器
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);
}
查看
@Html.DropDownListFor(model => model.SponsorID, Model.SponsorList);
,或者如果您分配了选择列表ViewBag
or if you assigned the select list to ViewBag
@Html.DropDownListFor(model => model.SponsorID, (SelectList)ViewBag.SponsorList);
这篇关于我不能让一个DropDownList从表填充。 EF和MVC4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!