0

I'm making simple CRUD application with ASP MVC 2. Now I'm having trouble with assignment (I guess) with ViewData[List] to List inside my View, it says NullReferenceException. I attach screenshot of my View code. I would be glad if someone shows me how to make it work correctly. enter image description here

UPD:

in case someone need code of Controller and View, here they are:

Controller (filename: BookController.cs under "Controllers" folder)

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

View (filename: Booklist.aspx under "Views\Book" folder)

<%@ 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>
t3rmin41
  • 668
  • 2
  • 8
  • 18

1 Answers1

0

Based off of your watch this is because the data coming from the ViewData["Books"] is not of type List<Book>. So, the as is returning a null.

It is of type List<BookStore.Book> and you are trying to cast to List<BookStore.Models.Book>

Justin Pihony
  • 66,056
  • 18
  • 147
  • 180
  • Thanks for pointing this out, after closer look at debugger watch I managed to organize imports correctly and now it's working. I should have guessed it on my own (and that's why I feel lame right now :/ ). – t3rmin41 May 21 '14 at 16:26