0
我正在学习MVC3,我无法找到一种方法来填充下拉列表。 尝试从StackOverFlow中的示例,无法正常工作。从我在网络上找到的一个项目尝试,并且不起作用。 Found this guy's tutorial on Youtube它给了我下面的错误:在MVC3中填充下拉列表不起作用
There is no ViewData item of type 'IEnumerable' that has the key 'Categ'.
现在我出的选项。
这是我得到的值list
(我认为):
public class Cat
{
DataBaseContext db;
public IEnumerable<MyCategory> Categories()
{
db = new DataBaseContext();
List<MyCategory> categories = (from b in db.BookCategory
select new MyCategory { name = b.Name, id = b.ID }).ToList();
if (categories != null)
{
var ocategories = from ct in categories
orderby ct.id
select ct;
return ocategories;
}
else return null;
}
}
public class MyCategory
{
public string name { get; set; }
public int id { get;set;}
}
这是Controller
:
// GET: /Entity/Create
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(BookEntity ent)
{
Cat ca= new Cat();
IEnumerable<SelectListItem> items = ca.Categories().Select(c => new SelectListItem
{
Text = c.name,
Value = c.id.ToString()
});
ViewBag.Categ = items;
db.BookEntity.Add(ent);
db.SaveChanges();
return RedirectToAction("Index");
}
这是View
:
<div class="editor-field">
@Html.DropDownList("Categ"," Select One ")
</div>
不知何故,它不适合我。我感谢任何帮助和建议。
它的工作,非常感谢你。我已经失去了这几个小时。 –
@Szalasi Szabolcs不客气 – heads5150
@ heads5150:我猜只是ViewData和ViewBag不同,ViewBag是'dynamic'类型,而ViewData是'dictionary'类型。那么它是如何工作的?有这些类型的东西吗? – RGR