Click here to Skip to main content
15,357,293 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
First of all, i am in process of learning Blazor. I keep getting 'unhandled error occured' when Create component should load. The problem is when i add <inputselect> to EditForm and @bind-Value to one of model's property and try to populate list with values from database.

What I have tried:

Create component:
<pre>@page "/products/create"
@inject HttpClient client
@inject NavigationManager uriHelper

<h1>Create new product</h1>
<hr />

<EditForm Model="@model" OnValidSubmit="@validSubmit">
    <div class="form-group">
        <label>Code :</label>
            <InputText @bind-Value="@model.Code"/>
            <ValidationMessage For="@(()=>model.Code)"/>
    <div class="form-group">
        <label>Name :</label>
            <InputText @bind-Value="@model.Name" />
            <ValidationMessage For="@(()=>model.Name)" />
    <div class="form-group">
        <label>Category :</label>
            <InputSelect @bind-Value="@model.Category">
                @foreach (var item in categories)
            <ValidationMessage For="@(()=>model.Category)" />

    ProductsViewModel model = new ProductsViewModel();

    string[] categories { get; set; }

    protected override async Task OnInitializedAsync()
        categories = await client.GetFromJsonAsync<string[]>("api/products/categories");

    async Task validSubmit()
        await client.PostAsJsonAsync("api/products", model);


        public string[] GetCategories()
            return categoriesService.GetAllAsync().Result.Select(e => e.Name).ToArray();

It populates categories array but it does not show Create component with populated list.
Updated 2-Mar-22 8:12am

1 solution

You need to look at the Blazor Component Lifecycle to understand why you have this problem. ref: ASP.NET Core Razor component lifecycle | Microsoft Docs[^]

Have a read of this section of the information: Handle incomplete async actions at render[^]

I recommend Blazor University – Learn the new .NET SPA framework from Microsoft[^] as a good learning resource.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900