Diogo Teixeira
Diogo Teixeira

Reputation: 91

My foreach statement is outputting 2 errors

When I try to output a table with a foreach statement, it outputs 2 errors saying that the MovieViewModel and the MovieVM dont exist.

This is part of the Index.cshtml file:

  @foreach (MovieViewModel item in MovieVM)
  {
    <tr>
      <td>@item.MovieName</td>
      <td>@item.MovieCategory</td>
      <td>@item.MovieYear
      <td>@item.MoviePrice</td>
    </tr>
  }
</table>

This is part of the MoviesController.cs file:

  List<MovieViewModel> MovieVM = new List<MovieViewModel>
  {
    new MovieViewModel {
      MovieID = movie.MovieID,
      MovieName = movie.MovieName,
      MovieDescription = movie.MovieDescription,
      MoviePrice = movie.MoviePrice,
      MovieCategory = movie.MovieCategory,
      MovieYear = movie.MovieYear
    },
  };

  return View(MovieVM);
}

It outputs these 2 errors about the foreach:

"The type or namespace 'EmployeeViewModel' does not exist in the namespace 'WebApplication3.Models '(are you missing an assembly reference?)"

and

"The name 'MovieVM' does not exist in the current context"

Upvotes: 0

Views: 109

Answers (2)

asd
asd

Reputation: 904

You must define the model type in the view.

@model IEnumerable<MovieViewModel>

@foreach (var item in Model)
{
   <tr>
    <td>@item.MovieName</td>
    <td>@item.MovieCategory</td>
    <td>@item.MovieYear</td>
    <td>@item.MoviePrice</td>
   </tr>
}

sample: https://dotnetfiddle.net/GA0yHD

Upvotes: 2

Diogo Teixeira
Diogo Teixeira

Reputation: 91

Does this DB connection have anything to do with the error?

 public ActionResult Index()
    {
        PAPEntities db = new PAPEntities();
        MoviesData movie = db.MoviesData.SingleOrDefault(x => x.MovieID == 1);

        List<MovieViewModels> MovieVM = new List<MovieViewModels>
            {
                new MovieViewModels {
                 MovieID = movie.MovieID,
                 MovieName = movie.MovieName,
                 MovieDescription = movie.MovieDescription,
                 MoviePrice = movie.MoviePrice,
                 MovieCategory = movie.MovieCategory,
                 MovieYear = movie.MovieYear
                    },
        };


        return View(MovieVM);
    }
}

Upvotes: 0

Related Questions