I'm testing blazor server (.net 6.05) on one of our projects and I have a following code:
@page "/"
@using Microsoft.EntityFrameworkCore
@using Microsoft.JSInterop
@inject IDbContextFactory<MyDbContext> DbContextFactory;
@code {
[Inject]
private IHttpContextAccessor HttpContextAccessor { get; set; } = default!;
MyDbContextContext { get; set; }
public Dish? RandomDish { get; set; }
public Region? Region { get; set; }
async Task getRandomDish()
{
var dish = await Context.Dishes.OrderBy(m => Guid.NewGuid()).FirstOrDefaultAsync();
RandomDish = dish;
}
async Task SaveDishName()
{
await Context.SaveChangesAsync();
}
protected override async Task OnInitializedAsync()
{
var a = HttpContextAccessor.HttpContext.User.Identity;
Context = await DbContextFactory.CreateDbContextAsync();
Region = await Context.Regions.SingleOrDefaultAsync(m => m.Name == "Italy");
await getRandomDish();
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (!firstRender) return;
}
}
<PageTitle>Index</PageTitle>
@if (RandomDish != null)
{
<h1>@RandomDish?.Name</h1>
<h2>@RandomDish?.DishId</h2>
<p>@Region?.Borders?.AsText()</p>
}<-- it errors here
<button @onclick="@(async () => await getRandomDish())">GET NEW DISH</button>
<div>
Change dish name
<input @bind="RandomDish.Name" />
<button @onclick="@(async () => await SaveDishName())">Save</button>
</div>
When I run the code, it throws following exception
System.NullReferenceException: 'Object reference not set to an instance of an object.'
****.Cms.Web.Pages.Index.RandomDish.get returned null.
I also tried "is not null" and referenceEquals(RandomDish, null), but always the same issue.
How am I supposed to do a null check, if getters will throw nulls :/
Issue disappears if I initialize dish with line under, but that's not a solution to a problem I guess.
public Dish? RandomDish { get; set; } = new Dish();
CodePudding user response:
You cannot have a null in @bind
.
<input @bind="RandomDish.Name" />
Surround the Save block with @if (RandomDish != null)
or something similar.
CodePudding user response:
Are you sure your expressions in the markup are being interpreted rightly? Try @(RandomDish?.Name)
and @(RandomDish?.DishId)
just to be sure. I suspect that @RandomDish?.Name
might be interpreted as @RandomDish
then a literal "?.Name"
.