Error {"The object reference was not defined as an instance of an object."} System.NullReferenceException MVC ASP.NET

0

Well, it gave me an error on the main page so I tried to pass the values from the search to the index. the error gives in line 35 of the index of the main page with the code:       @foreach (var item in Model) I'm doing a movie sales store, and the "admin" area code is as follows:

@model IEnumerable<MvcMovie.Models.Movie>

@{
    ViewBag.Title = "Index";
}

<h2>Filmes</h2>


    @Html.ActionLink("Novo Filme", "Create")
    @using (Html.BeginForm("Index", "Movies", FormMethod.Get))
    {
    <p>
        Género: @Html.DropDownList("movieGenre", "All")
        Titulo: @Html.TextBox("SearchString")
        <input type="submit" value="Procurar" />
    </p>
    }
    
<table class="table">
    <tr>
        <th>
            <label class="control-label col-md-13" for="Title">Titulo</label>
        </th>
        <th>
            <label class="control-label col-md-13" for="ReleaseDate">Data de Lançamento</label>
        </th>
        <th>
            <label class="control-label col-md-13" for="Genre">Género</label>      
         </th>
        <th>
            <label class="control-label col-md-13" for="Price">Preço</label>    
         </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Title)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.ReleaseDate)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Genre)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Price)
        </td>
        <td>
            @Html.ActionLink("Editar", "Edit", new { id=item.ID }) |
            @Html.ActionLink("Detalhes", "Details", new { id=item.ID }) |
            @Html.ActionLink("Apagar", "Delete", new { id=item.ID })
        </td>
    </tr>
}

</table>

a class is:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;

namespace MvcMovie.Models
{
public class Movie
{
    public int ID { get; set; }
    public string Title { get; set; }
    public DateTime ReleaseDate { get; set; }
    public string Genre { get; set; }
    public decimal Price { get; set; }
}
public class MovieDBContext : DbContext
{
    public DbSet<Movie> Movies { get; set; }
}
}

The Controller is:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using MvcMovie.Models;

namespace MvcMovie.Controllers
{
public class MoviesController : Controller
{
    private ApplicationDbContext db = new ApplicationDbContext();

    // GET: Movies
    public ActionResult Index(string movieGenre, string searchString)
    {
        var GenreLst = new List<string>();

        var GenreQry = from d in db.Movies
                       orderby d.Genre
                       select d.Genre;

        GenreLst.AddRange(GenreQry.Distinct());
        ViewBag.movieGenre = new SelectList(GenreLst);

        var movies = from m in db.Movies
                     select m;

        if (!String.IsNullOrEmpty(searchString))
        {
            movies = movies.Where(s => s.Title.Contains(searchString));
        }

        if (!string.IsNullOrEmpty(movieGenre))
        {
            movies = movies.Where(x => x.Genre == movieGenre);
        }

        return View(movies);
    }
    // GET: Movies/Create
    public ActionResult Create()
    {
        return View();
    }

    // POST: Movies/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "ID,Title,ReleaseDate,Genre,Price")] Movie movie)
    {
        if (ModelState.IsValid)
        {
            db.Movies.Add(movie);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(movie);
    }

    // GET: Movies/Edit/5
    public ActionResult Edit(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Movie movie = db.Movies.Find(id);
        if (movie == null)
        {
            return HttpNotFound();
        }
        return View(movie);
    }

    // POST: Movies/Edit/5
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "ID,Title,ReleaseDate,Genre,Price")] Movie movie)
    {
        if (ModelState.IsValid)
        {
            db.Entry(movie).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(movie);
    }

    // GET: Movies/Delete/5
    public ActionResult Delete(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Movie movie = db.Movies.Find(id);
        if (movie == null)
        {
            return HttpNotFound();
        }
        return View(movie);
    }

    // POST: Movies/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(int id)
    {
        Movie movie = db.Movies.Find(id);
        db.Movies.Remove(movie);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }

    
}
}

and the Main Index is:

@model IEnumerable<MvcMovie.Models.Movie>

@{
ViewBag.Title = "Página Principal";
}


<!DOCTYPE html>
<html>
<head>
<title>Small Bakery Products</title>
<style>
    table, th, td {
        border: solid 1px #bbbbbb;
        border-collapse: collapse;
        padding: 2px;
    }
</style>
</head>
<body>
<h1>Small Bakery Products</h1>
<table>
    <thead>
        <tr>
            <th>Title</th>
            <th>ReleaseDate</th>
            <th>Genre</th>
            <th>Price</th>
        </tr>
    </thead>
    <tbody>



        @foreach (var item in Model)
{
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Title)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.ReleaseDate)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Genre)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Price)
        </td>
    </tr>
}
        
    </tbody>
</table>
</body>
</html>
    
asked by anonymous 12.05.2018 / 00:29

1 answer

1

This error happens because the Movies list is coming null, See the Excption generated. One way to fix this is if it is null, it instantiates a list zered, so the table will be displayed, but without records, leave your Index like this:

// GET: Movies
public ActionResult Index(string movieGenre, string searchString)
{
    var GenreLst = new List<string>();

    var GenreQry = from d in db.Movies
                   orderby d.Genre
                   select d.Genre;

    GenreLst.AddRange(GenreQry.Distinct());
    ViewBag.movieGenre = new SelectList(GenreLst);

    var movies = from m in db.Movies
                 select m;

    if (!String.IsNullOrEmpty(searchString))
    {
        movies = movies.Where(s => s.Title.Contains(searchString));
    }

    if (!string.IsNullOrEmpty(movieGenre))
    {
        movies = movies.Where(x => x.Genre == movieGenre);
    }
     if(movies == null)
          return View(new List<Movie>());

    return View(movies);
}
    
12.05.2018 / 01:57