ErrorSystem.NullReferenceException: 'Object reference not set to an instance of an object.' Microsoft.AspNetCore.Mvc.Razor.RazorPage<TModel>.Model.get returned null.

João Machado 0 Reputation points
2024-05-22T22:37:02.95+00:00

Hello all,

I really need your help.

My Controller :

using Hayashi.DataAccess.Data;using Hayashi.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using System.Security.Claims;
namespace HayashiGreenStoreWeb.Areas
{
[Area("Customer")]
public class PostsController : Controller
{
    private readonly ApplicationDbContext _context;
    public PostsController(ApplicationDbContext context)
    {
        _context = context;
    }
    // GET: Posts
    public async Task<IActionResult> Index(int? pageNumber)
    {
        var applicationDbContext = _context.Posts.Include(q => q.User).Include(a => a.Answers);
        int pageSize = 3;
        return View(await PaginatedList<Post>.CreateAsync(applicationDbContext.AsNoTracking(), pageNumber ?? 1, pageSize));
    }
    // GET: Posts/Details/5
    public async Task<IActionResult> Details(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }
        var post = await _context.Posts
            .Include(p => p.User)
            .Include(p => p.Answers)
            .ThenInclude(a => a.User)
            .FirstOrDefaultAsync(m => m.Id == id);
        if (post == null)
        {
            return NotFound();
        }
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
        return View(post);
    }
    // GET: Posts/Create
    [Authorize]
    public IActionResult Create()
    {
        return View("Create");
    }
    // POST: Posts/Create
    // To protect from overposting attacks, enable the specific properties you want to bind to.
    // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [Authorize]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create([Bind("Id,Title,Description,IdentityUserId")] Post Post)
    {
        if (ModelState.IsValid)
        {
            _context.Add(Post);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        return View(Post);
    }
    [HttpPost]
    [Authorize]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> AddAnswer([Bind("Id,Content, PostId, IdentityUserId")] Answer answer)
    {
        if (ModelState.IsValid)
        {
            _context.Add(answer);
            await _context.SaveChangesAsync();
        }
        var post = await _context.Posts
            .Include(q => q.User)
            .Include(a => a.Answers)
            .ThenInclude(q => q.User)
            .FirstOrDefaultAsync(q => q.Id == answer.PostId);
        return View("Details", post);
    }
    // GET: Posts/Edit/5
    [Authorize]
    public async Task<IActionResult> Edit(int? id)
    {
        if (id == null || _context.Posts == null)
        {
            return NotFound();
        }
        var Post = await _context.Posts.FindAsync(id);
        if (Post.IdentityUserId != User.FindFirstValue(ClaimTypes.NameIdentifier))
        {
            return NotFound();
        }
        ViewData["IdentityUserId"] = new SelectList(_context.Users, "Id", "Id", Post.IdentityUserId);
        return View(Post);
    }
    // POST: Posts/Edit/5
    // To protect from overposting attacks, enable the specific properties you want to bind to.
    // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [Authorize]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Edit(int id, [Bind("Id,Title,Description,IdentityUserId")] Post Post)
    {
        if (id != Post.Id)
        {
            return NotFound();
        }
        if (ModelState.IsValid)
        {
            try
            {
                _context.Update(Post);
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!PostExists(Post.Id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
            return RedirectToAction(nameof(Index));
        }
        ViewData["IdentityUserId"] = new SelectList(_context.Users, "Id", "Id", Post.IdentityUserId);
        return View(Post);
    }
    // GET: Posts/Delete/5
    [Authorize]
    public async Task<IActionResult> Delete(int? id)
    {
        if (id == null || _context.Posts == null)
        {
            return NotFound();
        }
        var Post = await _context.Posts
            .Include(q => q.User)
            .FirstOrDefaultAsync(m => m.Id == id);
        if (Post.IdentityUserId != User.FindFirstValue(ClaimTypes.NameIdentifier))
        {
            return NotFound();
        }
        return View(Post);
    }
    // POST: Posts/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    [Authorize]
    public async Task<IActionResult> DeleteConfirmed(int id)
    {
        if (_context.Posts == null)
        {
            return Problem("Entity set 'ApplicationDbContext.Posts'  is null.");
        }
        var Post = await _context.Posts.FindAsync(id);
        if (Post != null)
        {
            _context.Posts.Remove(Post);
        }
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }
    private bool PostExists(int id)
    {
        return (_context.Posts?.Any(e => e.Id == id)).GetValueOrDefault();
    }
}
}

My view details view :

@model Hayashi.Models.Post
@using Microsoft.AspNetCore.Identity
@inject SignInManager<IdentityUser> SignInManager
@inject UserManager<IdentityUser> UserManager
@{
ViewData["Title"] = "Details";
<h3>@Model.Title</h3> 
<p>@Model.Description</p>
<p>- @Model.User.UserName</p>
<h4>All Answers:</h4>
@foreach (var answer in Model.Answers)
{
<p>@answer.Content - @answer.User.UserName</p>
<hr />
<form asp-action="AddAnswer">
<div class="form-group">
<textarea name="Content" class="form-control"></textarea>
</div>
<div class="form-group">
<input type="hidden" name="IdentityUserId" class="form-control" value="@UserManager.GetUserId(User)" />
</div>
<div class="form-group">
<input type="hidden" name="QuestionId" class="form-control" value="@Model.Id" />
</div>
<div class="form-group">
<input type="submit" class="btn btn-info" value="Submit" />
</div>
<a asp-action="Index">Back to List</a>.

Error Message : ErrorSystem.NullReferenceException: 'Object reference not set to an instance of an object.' Microsoft.AspNetCore.Mvc.Razor.RazorPage<TModel>.Model.get returned null.

When i click on submitbutton on detail give me this error..

I really need help to solve this..

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,308 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Ping Ni-MSFT 3,035 Reputation points Microsoft Vendor
    2024-05-23T02:38:27.1733333+00:00

    Hi @João Machado,

    The NullReferenceException means the model is null post back to frontend. You said it makes such error when click the submit button on details page, you need check the AddAnswer post method, the post variable post back to frontend with null value:

    var post = await _context.Posts .Include(q => q.User) .Include(a => a.Answers) .ThenInclude(q => q.User) .FirstOrDefaultAsync(q => q.Id == answer.PostId); 
    return View("Details", post);
    

    It needs PostId to query the data and return back to the details page. And you can check the details page, there is no such element named PostId but an input named QuestionId , so your backend cannot receive this property value which will cause the post variable cannot query data from database.

    Be sure set a hidden input named PostId :

    <input type="hidden" name="PostId" class="form-control" value="@Model.xxx" />
    

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
    Best regards,
    Rena

    0 comments No comments