I am very new to ASP.NET MVC so this would probably be an easy question. I followed the W3 Schools Movies tutorial and created a small database with fields Naslov (“Heading” in my language) Sadrzaj (“Content” in my language) and Datum (“Date”) which I want to use as blog posts and to list on main Index. This is my current code for Aktuelnosti.cs
namespace comp_2000.Models
{
public class Aktuelnosti
{
public int ID { get; set; }
public string Naslov { get; set; }
public string Sadrzaj { get; set; }
public DateTime Datum { get; set; }
}
public class AktuelnostiContext : DbContext
{
public DbSet<Aktuelnosti> Aktuelnosti { get; set; }
}
}
And this is my related view for Index.cshtml in Aktuelnosti, which works
@model IEnumerable<comp_2000.Models.Aktuelnosti>
<table border="1">
<tr>
<th>
@Html.DisplayNameFor(model => model.Naslov)
</th>
<th>
@Html.DisplayNameFor(model => model.Sadrzaj)
</th>
<th>
@Html.DisplayNameFor(model => model.Datum)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td width="20%">
@Html.DisplayFor(modelItem => item.Naslov)
</td>
<td width="60%">
@Html.DisplayFor(modelItem => item.Sadrzaj)
</td>
<td>
@Html.DisplayFor(modelItem => item.Datum)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
@Html.ActionLink("Preview", "Details", new { id=item.ID }) |
@Html.ActionLink("Delete", "Delete", new { id=item.ID })
</td>
</tr>
So, when I try the same code for Index.cshtml inside Home, which looks like this
@model IEnumerable<comp_2000.Models.Aktuelnosti>
@foreach (var item in Model)
{
<p>@Html.DisplayFor(modelItem => item.Naslov)</p>
<p>@Html.DisplayFor(modelItem => item.Sadrzaj)</p>
<p>@Html.DisplayFor(modelItem => item.Datum)</p>
<hr>
}
I get this
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 48:
Line 49:
Line 50: @foreach (var item in Model)
Line 51: {
Line 52: <p>@Html.DisplayFor(modelItem => item.Naslov)</p>
It says the problem is in foreach loop. What I am doing wrong? I just want the same data from one database displayed on two different pages.
Edit: There is also something about NullReferenceException that was unhandled by the user code. Hope this is of any use for you.
System.NullReferenceExceptionmeans that something is null. In this case, most likely theModelisnull. Make sure that the controller is passing the Model.