Click here to Skip to main content
15,886,110 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:
Razor
<pre>@page "/products/create"
@inject HttpClient client
@inject NavigationManager uriHelper

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

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

@code{
    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);
        uriHelper.NavigateTo("products");
    }
}

ProductsController:

C#
[Route("categories")]
        [HttpGet]
        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.
Posted
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.
 
Share this answer
 

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