How to send two lists as model in MVC

I am making a small ASP.NET MVC 3 test application with a bookshelf where I can list "Books" and loan and return them to / from "Loaners".

I want to show both my books and my Loaners in one view, and for this I created a ViewModel called BooksViewModel, but I can’t understand why I can’t list my "Books". I can do “foreach (var item in Model)” and just touch the “Book” inside it, none of the properties of the “Book”.

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 greatly appreciated!

+4
source share
1 answer

It looks like you have the wrong model type in the view declaration. Try:

 @model MyTest.ViewModels.BooksViewModel @foreach (var item in Model.Books) { @item.Title } 
+5
source

Source: https://habr.com/ru/post/1337288/


All Articles