我一直在使用 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";
}
}
然后总是出现“成功了!”即使它为空,发生了什么?
我尝试在谷歌上查找,但没有找到任何东西,不知道为什么我的值没有更新
因此,在阅读和深入研究后,进一步找到了一种更有效、更有效的方法,就是这样
@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