为什么我的 blazor 表单无法从输入字段获取任何值

问题描述 投票:0回答:1

我一直在使用 blazor,遇到了一个问题,找不到任何解决方案,我一直在尝试将文本添加到输入字段中,但它没有更新

@page "/"

<PageTitle>Form</PageTitle>

<h1 style="text-align:center">Form & Validation</h1>

<EditForm Model="person" OnValidSubmit="FormSubmit" FormName="Form">
    <DataAnnotationsValidator />
    <label>Name :</label>
    <InputText id="name" @bind-Value="person.Name" />

    <br />
    <br />

    <button type="submit" class="btn btn-primary">submit</button>
</EditForm>

<p>New Name : @person.Name</p>


@code {
    Person person = new Person();
    string displaySuccess, styleColor;

    private void FormSubmit()
    {
        displaySuccess = "Worked!";
        styleColor = "Green";
    }

    class Person
    {
        public string? Name { get; set; }
    }
}

我试过了

    {
        if (person != null)
        {
            displaySuccess = "Worked!";
            styleColor = "Green";
        }
        else
        {
            displaySuccess = "Wrong!";
            styleColor = "red";
        }
    }

然后总是出现“成功了!”即使它为空,发生了什么?

我尝试在谷歌上查找,但没有找到任何东西,不知道为什么我的值没有更新

c# html razor blazor user-input
1个回答
0
投票

因此,在阅读和深入研究后,进一步找到了一种更有效、更有效的方法,就是这样

@page "/"
@inject ILogger<Home> Logger

<EditForm Model="Model" OnSubmit="Submit" FormName="Starship1">
    <div>
        <label>
            Identifier:
            <InputText @bind-Value="Model!.Id" />
        </label>
    </div>

    <div>
        <button type="submit">Submit</button>
    </div>
</EditForm>

<br />
<br />

<p>Id : @sarshipId</p>

@code {
    [SupplyParameterFromForm]
    public Starship? Model { get; set; }
    string? sarshipId { get; set; }

    protected override void OnInitialized() => Model ??= new();

    private void Submit()
    {
        sarshipId = Model!.Id;
    }

    public class Starship
    {
        public string? Id { get; set; }
    }
}

而不是

Person person = new Person();
我可以做
protected override void OnInitialized() => Model ??= new();

这解决了我的问题:D

© www.soinside.com 2019 - 2024. All rights reserved.