I'm creating MVC view for an entity to get some data from my database.
I'm using visio studio. Solution built successfully. Only the "GetAll" view has problem, other methods like "GetByID" is working.
Here is the view, the error "System.NullReferenceException: Object reference not set to an instance of an object." appears on "@foreach(var department in Model)"
@model List<Contoso.Entities2.Department>
@{
ViewBag.Title = "Index";
}
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<h2>Department List</h2>
<table class="table table-bordered table-striped">
<tr>
<td>Id</td>
<td>Name</td>
<td>Budget</td>
<td>Start Date</td>
</tr>
@foreach(var department in Model)
{
<tr>
<td>@department.Id</td>
<td>@department.Name</td>
<td>@department.Budget</td>
<td>@department.StartDate</td>
</tr>
}
</table>
Here is my controller:
namespace ContosoMVC.Controllers
{
public class DepartmentController : Controller
{
DepartmentService _departmentService;
public DepartmentController()
{
_departmentService = new DepartmentService();
}
// GET: Department
public ActionResult Index()
{
var departments = _departmentService.GetDepartments();
//if it's empty, it will search the same name "index"
return View();
}
"GetAll" method in my repository:
public IEnumerable<Department> GetAll()
{
var departments = _dbContext.Departments.ToList();
return departments;
}
Model already set.
namespace Contoso.Entities2
{
public class Department
{
public int Id { get; set; }
//[Key]
[MaxLength(150)]
public string Name { get; set; }
public decimal Budget { get; set; }
//make it nullable using "?"
public DateTime? StartDate { get; set; }
[ForeignKey("Instructor")]
public int InstructorId { get; set; }
public string Location { get; set; }
public DateTime? CreatedDate { get; set; }
public string CreatedBy { get; set; }
public string UpdatedBy { get; set; }
public DateTime? UpdatedDate { get; set; }
public ICollection<Course> Courses { get; set; }
public Instructor Instructor { get; set; }
}
}
I expect to get all values from the columns I mentioned in Index View. The error "System.NullReferenceException: Object reference not set to an instance of an object." appears on "@foreach(var department in Model)"