InputSelect 不适用于客户端 blazor

InputSelect not working on client side blazor

我正在尝试编写一个表单以将对象插入数据库(通过 api POST 请愿书),一切正常,但 InputSelect 不工作。它向我显示了数据,但在我单击提交按钮时没有发送所选选项

表单代码:

@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; }
}

容器代码:

@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 和 Medico 模型:

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 浏览器调试工具给我这个错误:

    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

但是编译后的页面有正确的选项值:

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

Issue picture

我尝试删除并且没有出现上述错误,但是 POST 请愿书没有获取 InputSelect 数据并尝试插入一个 MedicoId 为空字段的对象

编辑:可能是 InputSelect 解析问题???

编辑 2:如果我将 Medicos[] 更改为 List,我没有遇到第一个错误,但是当我尝试提交时,我觉得它的值不正确,因为

编辑 3:

我设法通过 enet 回答并删除了 EditForm 中的 DataAnnotationsValidator,几乎成功了 api 请愿书,但我有这个不完整的对象:

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

paciente 和 medico 应该为空,这不是问题,这里的问题是 medicoId 为空并且没有意义,因为它正确显示了选项和值

简单的解决方案是只在 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>

终于可以用了!