Search code examples
c#asp.netasp.net-mvcrazor

Passing list to view in asp.net mvc


Here is my action method from controller.

public class MoviesController : Controller
{
        private MovieDBContext db = new MovieDBContext();

        // GET: /Movies/
        public ActionResult Index()
        {
            return View( db.Movies.ToList() );
        }
}

As it can be seen a List is being passed to View that is why I am expecting to work with it as Listin view but in View it works as IEnumerable

Following is the first line from View

@model IEnumerable<MVCWebApplication2.Models.Movie>

Why passed value that was List behaves as IEnumerable? Is IEnumerable super class of List?


Solution

  • List<T> implements the IEnumerable<T> interface:

    http://msdn.microsoft.com/en-us/library/6sh2ey19(v=vs.110).aspx

    It is typically a best practice to try to work with interfaces where possible to keep your code decoupled, so that's why the View was scaffolded like that. In this instance, you could pass any other Movie collection that implements IEnumerable<T> to your View, and your View would happily render without issue.

    So, imagine you have another Action in some other Controller like:

        public ActionResult Index()
        {
            Queue<Movie> movies = new Queue<Movie>();
            movies.Enqueue(db.Movies.Single(m => m.Title == "Flash Gordon"));
            movies.Enqueue(db.Movies.Single(m => m.Title == "Star Wars"));
            return View( "Movie/Index", movies );
        }
    

    Because Queue<T> implements IEnumerable<T>, movies will get rendered by the same View without having to make any changes to it. If your View was typed to List<Movies>, you would need to create a whole separate View to accommodate your Queue<Movies> model!