Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

C# ASP.NET MVC Basics Adding a List Page Finishing the List View

Walter Bueso
Walter Bueso
10,654 Points

Hard time understanding the use of model data in this video

I'm having a hard time understanding how @model ComicBookGallery.Model.ComicBook[] got the information we needed from the ComicBookRepository class. For a beginner like myself, It would have been easier to understand if the code was instead: @model ComicBookGallery.Data.ComicBookRepository.

1 Answer

James Churchill
STAFF
James Churchill
Treehouse Teacher

Walter,

Hey there! The MVC design pattern can take awhile to become familiar with, so don't worry if things are completely clear yet.

It's the controller's job to prepare the data for the view. So for our list page, we want our ComicBooksController.Index() method to get the data from the repository (by calling the repository's GetComicBooks() method) and then pass that array of ComicBook objects to the view via our call to the View() method.

Here's the code for the Index() method:

public ActionResult Index()
{
    var comicBooks = _comicBookRepository.GetComicBooks();

    return View(comicBooks);
}

Within the view, we can now access the array of ComicBook objects via the view's Model property, but MVC requires us to specify the data type for the Model property. We do that using a @model directive, like this:

@model ComicBookGallery.Models.ComicBook[]

Once we've "strongly typed" our view to be an array of ComicBook objects, we can then loop over the items in that array like this:

@foreach (var comicBook in Model)
{
}

The important thing to keep in mind is that it's the controller's job to talk to the repository to get the data and then pass that data along to the view. The view will typically never talk to the controller or the repository. You can think of the conversation between the controller and view as a one-sided conversation: the controller communicates to the view, but never the other way around.

I hope this helps.

Thanks, James