我正在学习MVC3,我找不到一种方法来填充下拉列表。 从StackOverFlow尝试的例子,没有工作。试过我在网上发现的一个项目,但是没有用。 Found this guy's tutorial on Youtube它给了我以下错误:
没有类型为'IEnumerable'的ViewData项 有'分类'键。
现在我没有选择。
这是我在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>
不知怎的,它对我不起作用。我感谢任何帮助和建议。
答案 0 :(得分:1)
修改您的操作方法以使用ViewData而不是ViewBag,并且View标记将起作用。
public ActionResult Create()
{
Cat ca= new Cat();
IEnumerable<SelectListItem> items = ca.Categories().Select(c => new SelectListItem
{
Text = c.name,
Value = c.id.ToString()
});
ViewData["Categ"] = items;
return View("Index");
}
[HttpPost]
public ActionResult Create(BookEntity ent)
{
db.BookEntity.Add(ent);
db.SaveChanges();
return RedirectToAction("Index");
}
您需要在GET操作中填充ViewData而不是POST操作。通过命名下拉列表,类和MVC约定将自动查看ViewData容器。