I have an issue when trying to render Razor component, I get a NullReferenceException
.
I have a component NewsCard
which represents a simple card that contains a summary about a news entry:
@using Web.Backend.Models
@code {
[Parameter]
public News? NewsData { get; set; }
}
<a href="/news/@NewsData?.Id">
<div class="news-card">
<img src="@NewsData?.TitleImage.ResolveObjectUri()"/>
<div class="news-card-data">
<div class="news-card-header">
<h3>@NewsData?.Title</h3>
<div class="news-card-header-info">
<p class="news-card-posted-by">@string.Format("{0} {1}", NewsData?.PostedBy.LastName, NewsData.PostedBy.FirstName)</p>
<p class="news-card-posted-at">@NewsData?.PostedAt</p>
</div>
</div>
<p>@NewsData?.Description</p>
</div>
</div>
</a>
I used this component fine in other component using
<NewsCard NewsData="news"/>
but when I try to use this component in a page like this
<component type="typeof(NewsCard)" render-mode="ServerPrerendered" params-NewsData="news"/>
or like this
await Html.RenderComponentAsync<NewsCard>(RenderMode.ServerPrerendered, new { NewsData = news });
I get a NullReferenceException
. Why? The news
variable has an object when I look in the debugger.
I'm trying to understand why it doesn't work and also, why I cannot just use same syntax like in a component:
<NewsCard NewsData="news"/>
Thanks
So I've figured it out, I forgot to populate additional fields in retrieved news from database. I've added this:
foreach (News newsPost in news)
{
dbContext.Entry(newsPost).Reference(p => p.PostedBy).Load();
dbContext.Entry(newsPost).Reference(p => p.TitleImage).Load();
}
And it fixed a problem.