我正在使用ASP MVC 2制作简单的CRUD应用程序。现在我在使用ViewData [List]到我的View里面的List时遇到了分配问题(我猜),它说NullReferenceException。我附上了我的View代码的截图。如果有人告诉我如何让它正常工作,我会很高兴。
UPD:
如果有人需要Controller和View的代码,这里是:
Controller(文件名:BookController.cs" Controllers"文件夹)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BookStore.Repositories;
using BookStore.Models;
using BookStore.Services;
namespace BookStore.Controllers
{
public class BookController : Controller
{
private IBookService bookService = new BookService();
//
// GET: /Book/Bookstore
[HttpGet]
public ActionResult Bookstore()
{
ViewData["BookStoreMessage"] = "Store of books welcomes you!";
ViewData["Books"] = bookService.findAllBooks();
return View("Booklist");
}
}
}
查看(文件名:Booklist.aspx" Views \ Book"文件夹)
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%@ Import Namespace="BookStore" // was: Namespace="BookStore.Models" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>List of available books</title>
</head>
<body>
<h2><%=Html.Encode(ViewData["BookStoreMessage"])%></h2>
<div>
<table>
<thead>
<th>ID</th>
<th>Title</th>
<th>Year</th>
<th>Price</th>
</thead>
<tbody>
<% foreach (Book bookitem in (ViewData["Books"] as List<Book>)) %>
<% { %>
<tr>
<td><% Response.Write(Html.Encode(bookitem.id)); %></td>
<td><%=Html.Encode(bookitem.name)%></td>
<td><%=Html.Encode(bookitem.year)%></td>
<td><%=Html.Encode(bookitem.price)%></td>
</tr>
<% } %>
</tbody>
</table>
</div>
</body>
</html>
答案 0 :(得分:0)
根据您的观看,这是因为来自ViewData["Books"]
的数据不属于List<Book>
类型。因此,as
返回null。
类型为List<BookStore.Book>
,您正在尝试转换为List<BookStore.Models.Book>