Asp.Net MVC return list to view

Viewed 3080

I am trying to return a list to my view. I can return it with @viewbag but i only get one entry from it . If i try to do return view(items) I get exception issues. what should I do ?

here is my controller

   foreach (var movie in item)
        {
            var items = _db.Movies.Where(s => s.imdbID.Equals(movie.Movieid)).ToList();
             ViewBag.Movies = items;
            return View(items);
        }

Here is my view

@foreach (var item in ViewBag.Movies)
{
<p> @item.Title </p>
 

}
3 Answers

First of all you must not return View() inside a loop.

What is the meaning there ?

var items = new List<Movies>();

      foreach (var movie in item)
            {
                items = items.Add(_db.Movies.Where(s => 
                                       s.imdbID.Equals(movie.Movieid)).ToList());
            }
    return View(items);

And if you are returning the list why do you need that ViewBag.

ViewBag is needed when you dont want to include any other model in Dto you are passing. So if you are passing list of type Movies and for example you need another list of different type you pass the other one on ViewBag.

Do this on your View:

@model List<Movies>
@foreach(var item in Model)
{
    <p> @item.Title </p>
}

Move your return outside the loop and remove the ViewBag, it looks like your controller is wrong, and some part of the View. I Would also change the Where to FirstOrDefault, because you expect only 1 Movie to be found in the db. And remove the .ToList(), because that does nothing right now. like this:

var items = new List<Movies>();

foreach (var movie in item)
{
  items.Add(_db.Movies.FirstOrDefault(s => s.imdbID.Equals(movie.Movieid)));
}

return View(items);

Also change your view to this:

@model IEnumerable<namespace.Models.movies>

@foreach(var item in Model)
{
   <p> @item.Title </p>
}

You should use your model in the view, not the Viewbag, because right now, the (items) does nothing.

Also, look up how to add to a list in c#, it feels like you have some more to learn there, you can check here: https://www.jennerstrand.se/add-object-to-list-in-c-sharp/

In view, you have to import the model of movies.

For example in view,

@model IEnumerable<projectName.models.movies>
@foreach(var item in Model)
{
    <p> @item.Title </p>
}
Related