2

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>
2
  • 1
    Your model needs to be a list of books, not a single book. Can't iterate over a single item. Try @model List<BookStore.Models.Book> Commented Dec 15, 2018 at 2:09
  • Yes! This worked, Thanks a lot! Commented Dec 15, 2018 at 2:12

2 Answers 2

5

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>
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.