简体   繁体   中英

NullReferenceException: Object reference not set to an instance of an object error in ASP.NET MVC

I'm new to ASP.NET MVC and I get the

"NullReferenceException: Object reference not set to an instance of an object"

exception when trying to display data from a database. I have the Movies and Reviews tables that are connected like this:

public class Movie
{
    public int MovieId { get; set; }
    public string Title { get; set; }

    [DataType(DataType.Date)]
    public DateTime ReleaseDate { get; set; }
    public string Genre { get; set; }
    public decimal Price { get; set; }

    public virtual ICollection<Review> Reviews { get; set; }
    
}
public class Review
{
    #region Review Properties
    [Key]
    public int ReviewId { get; set; }

    [Required(ErrorMessage = "Comment can't be empty.")]
    public string Comment { get; set; }

    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}")]
    public DateTime Date { get; set; }
    #endregion

    #region Dependencies
    [ForeignKey("Id")]
    public int MovieId { get; set; }
    public Movie Movie { get; set; }

    #endregion
}

The context file looks like this:

using Microsoft.EntityFrameworkCore;
using MvcMovie.Models;

namespace MvcMovie.Data
{
    public class MvcMovieContext : DbContext
    {
        public MvcMovieContext()
        {
        }

        public MvcMovieContext(DbContextOptions<MvcMovieContext> options)
            : base(options)
        {
        }

        public DbSet<Movie> Movies { get; set; }
        public DbSet<Review> Reviews { get; set; }
    }
}

I need to display reviews for each movie in the Details view, so I created a review adding section that works fine (the reviews are added to the database). Now, when I tried displaying the reviews of the current movie, I used this code in the View file:

@foreach (Review review in Model.Reviews)
{
    <div class="container">
        <div class="row">
            <div class="col-md-2"></div>
            <div class="col-md-8">
                <div>
                    <p>@review.Comment</p>
                    <small class="pull-right">@review.Date</small>
                </div>
            </div>
        </div>
    </div>
    <hr />
}

Also I should mention that the view uses this model: @model MvcMovie.Models.Movie and the Reviews controller looks like this:

 public class ReviewsController : Controller
    {
        private readonly MvcMovieContext _context = new MvcMovieContext();

        public ReviewsController(MvcMovieContext context)
        {
            _context = context;
        }

        public ActionResult New(Review review)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    review.Date = DateTime.Now;
                    _context.Reviews.Add(review);
                    _context.SaveChanges();
                    TempData["message"] = "Your review was added.";
                }
                catch (Exception)
                {
                }
            }

            return Redirect("/Movies/Details/" + review.MovieId.ToString());
        }
   }

The Movies controller (only the Details part that passes data to the view) looks like this:

  namespace MvcMovie.Controllers
    {
        public class MoviesController : Controller
        {
            private readonly MvcMovieContext _context;
    
            public MoviesController(MvcMovieContext context)
            {
                _context = context;
            }
            public async Task<IActionResult> Details(int? id)
            {
                if (id == null)
                {
                    return NotFound();
                }
    
                var movie = await _context.Movies
                    .FirstOrDefaultAsync(m => m.MovieId == id);
                if (movie == null)
                {
                    return NotFound();
                }
    
                return View(movie);
            }
        }
    }

The exception appears on the @foreach (Review review in Model.Reviews) line so I am guessing Model.Reviews is somehow NULL , but I don't know why that could happen since the Reviews table is not empty. Any advice for this?

Try to fix your details action:

 var movie = await _context.Movies.Include(r=>r.Reviews)
                    .FirstOrDefaultAsync(m => m.MovieId == id);
.....

and to prevent this error in the future, fix a view code too

@if ( Model.Reviews!=null)
{
  @foreach (Review review in Model.Reviews)
  {
....
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM