填充下拉列表在MVC3不工作
本文关键字:工作 MVC3 下拉列表 填充 | 更新日期: 2023-09-27 17:53:39
我正在学习MVC3,我找不到一种方法来填充下拉列表。从StackOverFlow尝试的例子,不工作。从我在网上找到的一个项目中尝试过,但不起作用。在Youtube上找到了这个家伙的教程,它给了我以下错误:
没有'IEnumerable'类型的ViewData项有键' category '
现在我没有选择了。
这就是我在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>
不知怎么的,它不适合我。感谢您的帮助和建议。
修改你的动作方法使用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操作而不是POST操作中填充ViewData。通过命名下拉列表类别以及MVC约定将自动查看ViewData容器