我正在做一个带有书架的小型ASP.NET MVC 3测试应用程序,我可以在其中列出“书籍”,并将这些内容借给“Loaners”。
我想在一个视图中显示我的书籍和我的Loaners,并因此创建了一个名为BooksViewModel的ViewModel,但我无法弄清楚为什么我无法列出我的“书籍”。我可以做“foreach(模型中的var项目)”,只触摸里面的“Books”,没有Books属性。
我的模特
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; }
}
}
我的控制器:
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);
}
我的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; }
}
我的观点
@model IEnumerable<MyTest.ViewModels.BooksViewModel>
@foreach (var item in Model.Books)
{
@item.Title
}
非常感谢任何提示或代码修复!
答案 0 :(得分:5)
在我看来,就像你在视图声明中得到了错误的模型类型一样。尝试:
@model MyTest.ViewModels.BooksViewModel
@foreach (var item in Model.Books)
{
@item.Title
}