简体   繁体   中英

ASP.NET MVC: Pass list of objects from Controller to View

So this piece of code is my Controller class. I am sending a list of books to the View

public class BooksController : Controller
{
     public ActionResult Index(int page = 0)
     {
          List<Book> data = BookRepository.GetInstance().getAllBooks();
          return this.View(data);
     }
}

So I wrote this on the top refering the model class

@model BookStore.Models.Book

When I try to iterate like the below code, it says, it does not contain public instance for GetEnumerator , but I returned a list of objects, how do I access each object in the list in the for loop?

<ul>
   @foreach(var book in Model)
   {

   }
</ul>

Problem is in the following line:

@model BookStore.Models.Book

You are passing List<Book> from controller to view but your view's model type is Book . So write the above line as follows:

@model List<BookStore.Models.Book>

You are passing the list of objects from the controller to view, so you have to use IEnumerable or List or IList keywords in your view's. SO you can use the following ways.

@model IEnumerable<BookStore.Models.Book>

OR

@model IList<BookStore.Models.Book>

OR

@model List<BookStore.Models.Book>

I hope it will work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM