我是 MVC 和 ASP.NET 的新手,希望学习一些知识,因此我尝试制作一些简单的应用程序来了解细节。
好吧,我正在尝试制作一个下拉框显示书籍列表,其中显示书名但发布 book_id [主键]
我得到的错误是::不存在键为“IEnumerable”类型的“book_id”的 ViewData 项。
以下是我的看法:
<p>
<label for="book_id">Book:</label>
<%= Html.DropDownList("book_id" , (IEnumerable<SelectListItem>)ViewData["Books"]) %>
<%= Html.ValidationMessage("book_id", "*") %>
</p>
这是我的控制器中的内容
// GET: /Home/Create
//This is the form creation.
[Authorize]
public ActionResult Create()
{
this.ViewData["Books"] =
new SelectList(_entities.BookSet.ToList(), "book_id", "Title");
return View();
}
//
// POST: /Home/Create
//This sends it to the DB
[AcceptVerbs(HttpVerbs.Post) , Authorize]
public ActionResult Create([Bind(Exclude="problem_id")] Problem inProblem)
{
try
{
// TODO: Add insert logic here
Models.User user = getUser(User.Identity.Name);
if (user != null)
{
inProblem.user_id = user.user_id;
}
_entities.AddToProblemSet(inProblem);
_entities.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
我的图书表看起来像这样
book_id
title
publisher
language
isbn
我假设这是一个微不足道的新手错误;但我没有太多运气弄清楚这一点。任何帮助都会很棒
更简单的解决方案是将 ViewData 元素命名为与下拉列表相同的名称:
this.ViewData["book_id"] = new SelectList(_entities.BookSet.ToList(), "book_id", "Title");
这将自动绑定:
<%= Html.DropDownList("book_id") %>
如果您想再次显示视图(就像在 catch 中所做的那样),您还需要在 Create 的 Post 版本中填充 ViewData["book_id"]。
[AcceptVerbs(HttpVerbs.Post) , Authorize]
public ActionResult Create([Bind(Exclude="problem_id")] Problem inProblem)
{
try
{
// TODO: Add insert logic here
Models.User user = getUser(User.Identity.Name);
if (user != null)
{
inProblem.user_id = user.user_id;
}
_entities.AddToProblemSet(inProblem);
_entities.SaveChanges();
return RedirectToAction("Index");
}
catch
{
this.ViewData["Books"] = new SelectList(_entities.BookSet.ToList(), "book_id", "Title");
// ViewData["book_id"] with example above.
return View();
}
}
注意:上面的 this.ViewData["Books"] 确实应该在 catch 中完成 - 它只是为了演示缺少的内容。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)