I’m doing a small ASP.NET MVC 3 test-app with a bookshelf where I can list “Books”, and loan and return these to/from “Loaners”.
I want to show both my Books and my Loaners on one view, and have therefor created a ViewModel called BooksViewModel but I cannot figure out why i can’t list my “Books”. I can do “foreach(var item in Model)” and only touch “Books” inside it, none of the Books properties.
My Model
namespace MyTest.Models
{
/// <summary>
/// Represents a book
/// </summary>
public class Book
{
public int ID { get; set; }
public string Title { get; set; }
public string Author { get; set; }
public string ISBN { get; set; }
public virtual Loaner LoanedTo { get; set; }
}
/// <summary>
/// Represents a Loaner
/// </summary>
public class Loaner
{
public int ID { get; set; }
public string Name { get; set; }
public virtual ICollection<Book> Loans { get; set; }
}
/// <summary>
/// Bookshelf Database Context
/// </summary>
public class BookshelfDb : DbContext
{
public DbSet<Book> Books { get; set; }
public DbSet<Loaner> Loaner { get; set; }
}
}
My Controller:
BookshelfDb bookshelf = new BookshelfDb();
public ActionResult Index()
{
var books = from book in bookshelf.Books
select book;
var loaners = from loaner in bookshelf.Loaner
select loaner;
var bookViewModel = new BooksViewModel(books.ToList(),loaners.ToList());
return View(bookViewModel);
}
My ViewModel
public class BooksViewModel
{
public BooksViewModel(List<Book> books, List<Loaner> loaners)
{
this.Books = books;
this.Loaners = loaners;
}
public List<Book> Books { get; private set; }
public List<Loaner> Loaners { get; private set; }
}
My View
@model IEnumerable<MyTest.ViewModels.BooksViewModel>
@foreach (var item in Model.Books)
{
@item.Title
}
Any hints or code fixes would be much appreciated!
Looks to me like you got the type of the model wrong in the view declaration. Try: