我正在开发Blazor应用程序,并尝试通过URL.
但是我收到错误:
System.NullReferenceException:
"Object reference not set to an instance of an object." productDTO было null.
Catalog.razor 是一个页面,我在该页面上显示产品列表,单击后,转到传递 ProductId 参数的 ProductCard 组件:
@code {
protected override async Task OnInitializedAsync()
{
var products = await ProductRepository.GetAll();
productsDTO = products.Select(p => new ProductDTO
{
Name = p.Name,
Img = p.Img,
Description = p.Description,
Price = p.Price
}).ToList();
}
private void OnProductClick(ProductDTO product)
{
NavigationManager.NavigateTo($"/ProductCard/{product.Id}");
}
}
一切正常并显示所需的一切。
ProductCard.razor 是一个以 ProductId 作为参数的组件:
@using Core
@using Core.DTO;
@using Core.Entities
@using Infrastructure.Repository
@page "/ProductCard/{ProductId:guid}"
@rendermode InteractiveServer
@inject ProductRepository productRepository
<div class="ProductCard">
<img src="@productDTO.Img" />
<div class="card-body"
<span class ="title">@productDTO?.Name</span>
<span class="price">@productDTO?.Price</span>
<span class="description">@productDTO?.Description</span>
<span class="specs">@productDTO?.Specs</span>
</div>
</div>
@code {
[Parameter]
public Guid productId { get; set; }
private ProductDTO productDTO;
protected override async Task OnInitializedAsync()
{
var product = await productRepository.GetByIdAsync(productId);
if (product != null)
{
productDTO = new ProductDTO
{
Id = product.Id,
Name = product.Name,
Img = product.Img,
Description = product.Description,
Price = product.Price,
Specs = product.Specs
};
}
else
{
Console.WriteLine("Продукт не найден");
}
}
}
}
Blazor 无法将 ProductId 识别为 ProductCard 中的参数,并且出现异常。