Please see the Error section below. Other related code is as follows:
Model:
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public List<Post> Posts { get; set; }
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int BlogId { get; set; }
public Blog Blog { get; set; }
}
BlogPostController
public IActionResult Index()
{
return View("~/Views/BlogsTest/Index.cshtml");
}
View [Index.cshtml]:
@model IEnumerable<ASPCoreCodeFirstApp.Models.Blog>
<p>
<a asp-controller="BlogPost" asp-action="Create">Create New</a>
</p>
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.Url)
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Url)
</td>
<td>
<a asp-controller="BlogPost" asp-action="Edit" asp-route-id="@item.BlogId">Edit</a>
</td>
<td>
<a asp-controller="BlogPost" asp-action="Create" asp-route-id="@item.BlogId">Edit</a>
</td>
</tr>
}
</tbody>
</table>
Error at @foreach (var item in Model)....line
:
I can see the Index method gets called and when I put the breakpoint at the @foreach (var item in Model)
line of Index.cshtml file I get Model as null and the browser throws the following error. Blogs table does have data. Even if it did not have data the foreach loop should have returned empty result instead of an NULL exception error. The view relative path in the Index action method seems write since Index.cshtml view does get called. What I may be missing?:
NullReferenceException: Object reference not set to an instance of an object.
MoveNext in Index.cshtml, line 22
Folder Hierarchy:
Model above is in Model.cs file highlighted below: