'InputSelect not working on client side blazor

I'm trying to code a form to insert Objects into a database (via api POST petition), everything works fine but InputSelect is not working. It shows me the data but doesn't sends the selected option when I click the submit button

The form code:

@using ClinicaVistaalegre.Shared.Models
@inject HttpClient Http

<EditForm Model="@Cita" OnValidSubmit="@OnValidSubmit">
    <h3>Crear cita</h3>
    <hr />
    <div class="form-group row">
        <label for="Motivo" class="col-sm-2 col-form-label">
            Motivo
        </label>
        <div class="col-sm-10">
            <InputText id="Motivo" class="form-control" placeholder="Motivo"
                       @bind-Value="Cita.Motivo" />
        </div>
    </div>
    <div class="form-group row">
        <label for="FechaHora" class="col-sm-2 col-form-label">
            Fecha y Hora
        </label>
        <div class="col-sm-10">
            @*<inp @bind=Cita.FechaHora @bind:format="yyyy-MM-ddTHH:mm" type="datetime-local"/>*@
            <InputDate id="FechaHora" class="form-control" placeholder="FechaHora"
                       @bind-Value="Cita.FechaHora" />
        </div>
    </div>
    <div class="form-group row">
        <label for="MedicoId" class="col-sm-2 col-form-label">
            Contacto
        </label>
        <div class="col-sm-10">
            <InputSelect @bind-Value="Cita.MedicoId" class="form-control">
                @foreach (Medico m in medicos)
                {
                    <option value="@m.Id">@m.Apellidos</option>
                }
        </InputSelect>
    </div>
</div>

<div class="form-group row">
    <label for="PacienteId" class="col-sm-2 col-form-label">
        Paciente
    </label>
    <div class="col-sm-10">
        <div class="col-sm-10">
        <InputText id="Paciente" class="form-control" placeholder="Paciente"
                   @bind-Value="Cita.PacienteId" />
    </div>
        </div>
    </div>
    <button type="submit" class="btn btn-success">@TextoBoton</button>
    <DataAnnotationsValidator/>
</EditForm>

@code {
    private Medico[]? medicos;

    protected override async Task OnInitializedAsync() => 
        medicos = await Http.GetFromJsonAsync<Medico[]>("api/Medicos");

    [Parameter] public Cita Cita { get; set; } = new Cita();
    [Parameter] public String TextoBoton { get; set; } = "Guardar";
    [Parameter] public EventCallback OnValidSubmit { get; set; }
}

Container code:

@page "/creacitas"
@using ClinicaVistaalegre.Shared.Models
@using System.Net.Http.Json
@inject HttpClient Http
@inject NavigationManager NavMan


<PageTitle>Citas</PageTitle>

<h1>Crear cita</h1>

<FormularioCita TextoBoton="Crear cita" OnValidSubmit="@CrearCita" Cita="@cita"/>

@code {
    Cita cita = new Cita();

    async Task CrearCita(){
        //var json = JsonConvert.SerializeObject(cita);
        //await Http.PostAsync("api/Citas", new StringContent(json, UnicodeEncoding.UTF8, "application/json"));
        //await Http.PostAsync("api/Citas", new StringContent(JsonConvert.SerializeObject(json)));
        //UriHelper.
        //var addItem = new TodoItem { Name = newItemName, IsComplete = false };
        
        HttpResponseMessage mensaje = await Http.PostAsJsonAsync("api/Citas", cita);

        if (mensaje.IsSuccessStatusCode)
        {
            NavMan.NavigateTo("fetchcitas");
        }

    }
}

Cita and Medico Model:

public class Cita
    {
        public int Id { get; set; }

        [Required]
        public string PacienteId { get; set; }

        [JsonProperty(Required = Required.AllowNull)]
        public Paciente? Paciente { get; set; }

        [Required]
        public string MedicoId { get; set; }

        [JsonProperty(Required = Required.AllowNull)]
        public Medico? Medico { get; set; }

        public string? Motivo { get; set; }
        public DateTime FechaHora { get; set; }
    }

public class Medico
    {
        public string Id { get; set; }
        public string Apellidos { get; set; }
        public string Especialidad { get; set; }

        [JsonProperty(Required = Required.AllowNull)]
        public List<Cita> Citas { get; set; }
        [JsonProperty(Required = Required.AllowNull)]
        public List<Mensaje> Mensajes { get; set; }
    }

Chrome browser debug tool give me this error:

    blazor.webassembly.js:1 crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
      Unhandled exception rendering component: Object reference not set to an instance of an object.
System.NullReferenceException: Object reference not set to an instance of an object.
   at ClinicaVistaalegre.Client.Shared.FormularioCita.<BuildRenderTree>b__0_8(RenderTreeBuilder __builder3) in C:\Users\santanitaxx1050\Desktop\ClinicaVistaalegre\ClinicaVistaalegre\Client\Shared\FormularioCita.razor:line 32
   at Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder.AddContent(Int32 sequence, RenderFragment fragment)
   at Microsoft.AspNetCore.Components.Forms.InputSelect`1[[System.String, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].BuildRenderTree(RenderTreeBuilder builder)
   at Microsoft.AspNetCore.Components.ComponentBase.<.ctor>b__6_0(RenderTreeBuilder builder)
   at Microsoft.AspNetCore.Components.Rendering.ComponentState.RenderIntoBatch(RenderBatchBuilder batchBuilder, RenderFragment renderFragment, Exception& renderFragmentException)
window.Module.s.printErr @ blazor.webassembly.js:1

But the compiled page has the correct option value:

<option value="b04efe29-a306-40b1-8799-41b99b215a69">sanchez luque</option>

Issue picture

I tried removing and the error above doesn't appear but the POST petition doesn't get the InputSelect data and tries to insert an object with MedicoId null field

Edit: Maybe an InputSelect parsing problem???

Edit 2: If i change Medicos[] to List I don't have the first error but when I try to submit it appears me like the value it's not correct due to the

Edit 3:

I managed to make an almost successfull api petition with enet answer and removing DataAnnotationsValidator in EditForm but I have this incomplete object:

{
  "id": 0,
  "pacienteId": "1d49f54a-91cb-4980-8983-9a70bd1c668d",
  "paciente": null,
  "medicoId": null,
  "medico": null,
  "motivo": "pruebacreate",
  "fechaHora": "0001-01-01T00:00:00"
}

paciente and medico should be null, that's not the problem, the problem here is that medicoId is null and it has no sense because it shows the options and values correctly



Solution 1:[1]

The simple solution is to only add an empty value option into InputSelect

InputSelect:

<InputSelect id="Medico" class="form-control" placeholder="Medico" @bind-Value="@Cita.MedicoId">
            <option value="">---</option>
            @if(medicos!=null){
                foreach (Medico m in medicos)
            {
                <option value="@m.Id">@m.Apellidos</option>
            }
            }
        </InputSelect>

It is finally working!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 suntunutuxx