user3461957
user3461957

Reputation: 163

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?

Upvotes: 3

Views: 9108

Answers (2)

Mister Epic
Mister Epic

Reputation: 16713

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!

Upvotes: 4

arserbin3
arserbin3

Reputation: 6148

As Chris mentioned, List<T> implements IEnumerable<T>, so that is why it is valid for the View's model to be:

 @model IEnumerable<MVCWebApplication2.Models.Movie>

Since you said you want to use it as a List, the List also implements IList<T> which should provide you with the functionality you were expecting to have in your view.

You can make use of the List methods like so:

@model IList<MVCWebApplication2.Models.Movie>
<div>
    First movie: @Model.First().Name
</div>

@Model.Count Action Movies:
<ul>
    @foreach (var item in Model.Where(x => x.Type = "ActionMovie"))
    {
        <li>@item.Name - @item.Description</li>
    }
</ul>

Upvotes: 3

Related Questions