Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC - Returning two repositories to the View

Tags:

asp.net-mvc

I am currently learning ASP.NET MVC so please excuse my question if it has been asked or seems rather simple, but if I could get some help I would greatly appreciate it.

I am trying to return two different repositories to the View. I am going through ASP.NET MVC's tutorials and I thought I would try taking it a step further. I can display Movies from the Movie table in the database just fine but I also want to display data from the Actors table on the same as well and I am not sure how to go about doing this. For displaying the Movies I was following the Repository pattern.

I hope this makes sense.

Thanks,

like image 673
flowy Avatar asked Dec 17 '22 09:12

flowy


1 Answers

Create a new class that has both a list of Movies and Actors in it:

public class MoviesAndActorsModel
{
    public IList<Movie> Movies { get; set; }
    public IList<Actor> Actors { get; set; }
}

Then, in your controller action, instantiate an object of type MoviesAndActorsModel that is populated from your repository:

public ActionResult List()
{
    MoviesAndActorsModel model = new MoviesAndActorsModel();

    model.Movies = _repository.GetMovies();
    model.Actors = _repository.GetActors();

    return View(model);
}

Now make sure your view inherits from ViewPage<MoviesAndActorsModel> and you should be able to access both the movies and actors like so:

<% foreach (Movie movie in Model.Movies) { %>
    <%= movie.Title %>
<% } %>

<% foreach (Actor actor in Model.Actors) { %>
    <%= actor.Name %>
<% } %>
like image 121
Kevin Pang Avatar answered Jan 11 '23 16:01

Kevin Pang