I'm learning about ViewModels in C# ASP.NET MVC 3, and I'm stuck at displaying data from the ViewModel in my View.
The Models:
public class Author
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Book> Books { get; set; }
}
public class Book
{
public int Id { get; set; }
public int AuthorId { get; set; }
public string Title { get; set; }
public decimal Price { get; set; }
}
In my Index View I want to show general lists of both Authors and Books. I have made a ViewModel for this:
public class BookIndexViewModel
{
public List<Book> Books { get; set; }
public List<Author> Authors { get; set; }
}
Here is my Index() action method from the controller:
public ViewResult Index()
{
BookIndexViewModel viewModel = new BookIndexViewModel();
viewModel.Authors = db.Authors.ToList();
// leaving Books empty for now
return View(viewModel);
}
I have a strongly typed Index View where I want to show the list of Authors:
@model IEnumerable<NewBookStore.ViewModels.BookIndexViewModel>
@foreach (var author in Model.Authors) {
<tr>
<td>
@author.Name
</td>
</tr>
}
It's the Model.Authors part that doesn't work. When I type Model. and wait for IntelliSense to show Authors, it isn't listed. The error description is:
'System.Collections.Generic.IEnumerable' does not contain a definition for 'Authors' and no extension method 'Authors' accepting a first argument of type 'System.Collections.Generic.IEnumerable' could be found (are you missing a using directive or an assembly reference?)