0

I've two models and I'd like to use them all in one View.

public class Author
    {
        public int Id { get; set; }
        [Required]
        public string Name { get; set; }
        //public virtual List<Book> Books { get; set; }
     }




public class Genre
    {
        public int Id { get; set; }
        [Required]
        public string Name { get; set; }
       // public virtual List<Book> Books { get; set; }
    }

I'd like to use these in one View. This is a bookstore app. With this, I'd like to display genres and author's names on my Home page.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Anthino Russo
  • 59
  • 1
  • 8
  • youll need to create a new ViewModel and then bring these classes in. – Simon Price Jun 15 '18 at 20:41
  • Look up the term "ViewModel". It has been covered dozens of times here on Stackoverflow (for example: https://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc) – Marco Jun 15 '18 at 20:42
  • What research have you done???? There are tons of example on the web regarding this topic!!! – Eric Jun 15 '18 at 21:00

1 Answers1

0

This is what you need to do and return the combined view model back to the view

public class Author
{
    public int Id { get; set; }
    [Required]
    public string Name { get; set; }
    //public virtual List<Book> Books { get; set; }
}

public class Genre
{
    public int Id { get; set; }
    [Required]
    public string Name { get; set; }
    // public virtual List<Book> Books { get; set; }
}

// This is what you bring back to your View
public class CombinedViewModel {

    public Genre Genre { get; set; }
    public Author Author {get; set;}
}
Simon Price
  • 3,011
  • 3
  • 34
  • 98