MrRobot9
MrRobot9

Reputation: 2684

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>

Upvotes: 2

Views: 5519

Answers (2)

Shivaraja D
Shivaraja D

Reputation: 86

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.

Upvotes: 2

TanvirArjel
TanvirArjel

Reputation: 32119

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>

Upvotes: 5

Related Questions