Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using two models in one controller?

I currently have an application with a home page that shows a list of ten movies based on the date they were "created", or entered into the database. I would also like to show a list of the top ten movies based on the rating of each movie. Is there a way to pass in another model or alter my current ViewModel to do this? Here is the Index section of my Home Controller:

    public ActionResult Index()
    {
        var model =
            _db.Movies
                .OrderByDescending(m => m.DateEntered)
                .Take(10)
                .Select(m => new MovieListViewModel 
                {
                    Id = m.Id,
                    Title = m.Title,
                    Genre = m.Genre,
                    ReleaseDate =  m.ReleaseDate,
                    CountOfReviews = m.Reviews.Count()
                });

        return View(model);

    }

And the ViewModel being passed in:

public class MovieListViewModel
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Genre { get; set; }

    [Display(Name="Year Released")]
    public DateTime ReleaseDate { get; set; }
    public int CountOfReviews { get; set; }
}
like image 455
Ron Saylor Avatar asked Jul 29 '26 22:07

Ron Saylor


1 Answers

Create a model that encompasses both lists:

public class MovieListViewModel
{
  public List<MovieModel> Top10ByCreated { get; set; }
  public List<MovieModel> Top10ByRating { get; set; }
}

public class MovieModel
{
  public int Id { get; set; }
  public string Title { get; set; }
  public string Genre { get; set; }

  [Display(Name="Year Released")]
  public DateTime ReleaseDate { get; set; }
  public int CountOfReviews { get; set; }
}

Then in your controller:

var model = new MovieListViewModel();

model.Top10ByCreated = ...
model.Top10ByRating = ...

return View(model);

In your view, use MovieListViewModel as your model and use your two lists as needed.

like image 180
Matt Houser Avatar answered Aug 01 '26 13:08

Matt Houser



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!