'Do I have to manipulate the Model data in Controller to pass to View?
I have two tables: Cache (date (timestamp) and site) and SiteContent where I store words and their counts. One site has many SiteContents entries. I want to send SiteContents to View.
Cache:
[Required]
public string Site { get; set; }
[Required]
public DateTime Date { get; set; }
public virtual ICollection<Cash> SiteContent { get; set; }
SiteContent:
[Required]
public int CashId { get; set; }
public virtual Cache Site { get; set; }
[Required]
public string Word { get; set; }
[Required]
public uint Count { get; set; }
Code of controller:
public IActionResult Index()
{
//Console.WriteLine(_context.Caches.ToArray()[0].Site);
//Console.WriteLine(_context.SiteContents.ToArray()[0].Word);
//Console.WriteLine(_context.SiteContents.ToArray()[0].Site.Site);
return View(_context.SiteContents.ToList());
}
View code:
@using ParserWeb.Models
@model IEnumerable<SiteContent>
@{
ViewData["Title"] = "Home Page";
}
<table class="table">
@foreach (SiteContent c in Model)
{
<tr> <td>@c.Site.Date</td> <td>@c.Site.Site</td> <td>@c.Word</td> <td>@c.Count</td> </tr>
}
</table>
How come the code only works if I uncomment? Otherwise there is
System.NullReferenceException: "Object reference not set to an instance of an object."
Solution 1:[1]
@foreach (SiteContent c in Model)
{
<tr> <td>@c.Site.Date</td> <td>@c.Site.Site</td> <td>@c.Word</td> <td>@c.Count</td> </tr>
}
You wanna use @c.Site.Date but you don't include Site.
Site = null and you wanna use Site.Date, (property of null) that's the reason of exception.
Answer:
return View(_context.SiteContents.Include(s => s.Site).ToList());
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
