Home > OS >  ASP.NET MVC - Get Exception: Object reference not set to an instance of an object
ASP.NET MVC - Get Exception: Object reference not set to an instance of an object

Time:08-09

I am making a page and on this page, there is a table. I want to filter Name from the table. And I wrote code like this:

Index.cshtml:

@using StudentApp.Models.Entity
@model List<StudentTable>
@{
    ViewData["Title"] = "Manage Student";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<br />
<h1>Manage Student</h1>
<br />
@using (Html.BeginForm("Index", "Students", FormMethod.Get))
{
    <p>
        <b>Student Name:</b> @Html.TextBox("p");
        <input type="submit" value="Ara">
    </p>
}
<table id="tbl1" >
    <tr>
        <th>
            Student ID
        </th>
        <th>
            Student Name
        </th>
        <th>
            Student Class
        </th>
        <th>
            Edit
        </th>
        <th>
            Delete
        </th>
    </tr>
    <tbody>
        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @item.Id
                </td>
                <td>
                    @item.Name
                </td>
                <td>
                    @item.Class.ClassName // Error
                </td>
                <td>
                    <a href="/StudentTable/EditStudent/@item.Id" >Edit</a>
                </td>
                <td>
                    <a href="/StudentTable/Delete/@item.Id" >Delete</a>
                </td>
            </tr>
        }
    </tbody>
</table>

<a href="/StudentTable/AddStudent"  >Add Student</a>


<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link href="~/lib/bootstrap/dist/css/bootstrap.css" rel="stylesheet" />
<link href="https://cdn.datatables.net/1.10.15/css/dataTables.bootstrap.min.css" rel="stylesheet" />
<link href="https://cdn.datatables.net/responsive/2.1.1/css/responsive.bootstrap.min.css" rel="stylesheet" />
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/dataTables.bootstrap4.min.js "></script>  

<script>
    $('#tbl1').dataTable({});
</script>

StudentController.cs:

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using StudentApp.Models.Entity;
using System.Linq;

namespace StudentApp.Controllers
{
    public class StudentTableController : Controller
    {
        StudentDatabaseContext db = new StudentDatabaseContext();
        public IActionResult Index(string p)
        {
            var degerler = from d in db.StudentTables select d;
            if (!string.IsNullOrEmpty(p))
            {
                degerler = degerler.Where(m => m.Name.Contains(p));
            }
            return View(degerler.ToList());
        }
        [HttpGet]
        public ActionResult AddStudent()
        {
            List<SelectListItem> GetClass = new List<SelectListItem>();
            foreach (var item in db.ClassTables.ToList())
            {
                GetClass.Add(new SelectListItem { Text = item.ClassName, Value = item.Id.ToString() });
            }
            ViewBag.ClassList = GetClass;
            return View(new StudentTable());
        }
        [HttpPost]
        public ActionResult AddStudent(StudentTable st)
        {
            db.StudentTables.Add(st);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        public IActionResult Delete(int id)
        {
            var student = db.StudentTables.SingleOrDefault(i => i.Id == id);
            db.StudentTables.Remove(student);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        [HttpGet]
        public ActionResult EditStudent(int id)
        {
            var info = db.StudentTables.SingleOrDefault(i => i.Id == id);
            List<SelectListItem> GetClass = new List<SelectListItem>();
            foreach (var item in db.ClassTables.ToList())
            {
                GetClass.Add(new SelectListItem { Text = item.ClassName, Value = item.Id.ToString() });
            }
            ViewBag.ClassT = GetClass;
            return View("EditStudent", info);

        }
        [HttpPost]
        public ActionResult EditStudent(StudentTable p)
        {
            var StudentT = db.StudentTables.SingleOrDefault(i => i.Id == p.Id);
            StudentT.Name = p.Name;
            StudentT.ClassId = p.ClassId;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
    }
}

StudentTable.cs:

using System;
using System.Collections.Generic;

namespace StudentApp.Models.Entity
{
    public partial class StudentTable
    {
        public int Id { get; set; }
        public string? Name { get; set; }
        public int ClassId { get; set; }

        public virtual ClassTable? Class { get; set; }
    }
}

When I run the codes, I get the following error on the Index.cshtml page:

enter image description here

Why could this be? How can I fix the error? Thanks in advance for your help.

CodePudding user response:

You need an eager loading for the StudentTable entities to load its related Class entities.

public IActionResult Index(string p)
{
    ...

    return View(degerler
        .Include(x => x.Class)
        .ToList());
}

While Class property is nullable type in StudentTable, use ?. null-conditional operator to prevent accessing to inner property when the parent is null.

View

@item.Class?.ClassName
  • Related