【问题标题】:MVC - No Viewdata item with key of type 'IEnumerable<SelectListItem>'MVC - 没有具有“IEnumerable<SelectListItem>”类型键的 Viewdata 项
【发布时间】:2010-01-25 01:20:30
【问题描述】:

我是 MVC 和 ASP.NET 的新手,想学点东西,所以我尝试制作一些琐碎的应用程序来了解其中的来龙去脉。

好吧,我正在尝试让一个下拉框显示书籍列表,它会显示书名但发布 book_id [主键]

我得到的错误是:没有 ViewData 项,键为“IEnumerable”类型的键“book_id”。

这是我的看法:

    <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();
    }
}

我的 Books 表看起来像这样

        book_id
        title
        publisher
        language
        isbn

我假设这是一个微不足道的新手错误;但我没有太多运气弄清楚。任何帮助都会很棒

【问题讨论】:

  • 请在我的回复中查看缺少的行的附加代码(为简单起见,在 catch 语句中)

标签: c# asp.net-mvc


【解决方案1】:

更简单的解决方案是将 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 中完成 - 它只是为了演示缺少的内容。

【讨论】:

  • @PSU_Kardi - 您需要完全按照您现在在控制器中创建的“发布”版本中所做的方式填充 ViewData["Books"]。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-11
  • 2015-04-26
  • 2020-06-28
  • 2020-08-20
  • 2011-02-20
  • 2015-03-11
相关资源
最近更新 更多