我有一个Blazor页面,用于创建一个用户,当按钮被单击时,我想显示一个加载文本。当它完成时,我想隐藏文本,这是我的代码:
<AuthorizeView>
<Authorized>
@if (@IsLoading) {
<div>Loading</div>
} else {
<div class="add-user">
<PageHeader Text="Add User" />
<form Model="NewUser" class="user-form">
<div class="line">
<label for="name">Name</label>
<input type="text" id="name" @bind="NewUser.Name" />
</div>
<div class="line">
<label for="email">Email</label>
<input type="email" id="email" @bind="NewUser.Email" />
</div>
<div class="line">
<div>
<label>Gender</label>
</div>
<div>
<label for="male">Male</label>
<input type="radio" id="male" name="gender" value="Male" @onchange="UpdateGender" checked="@IsMaleRadioButtonChecked" />
<label for="female">Female</label>
<input type="radio" id="female" name="gender" value="Female"
@onchange="UpdateGender" checked="@IsFemaleRadioButtonChecked"/>
</div>
</div>
<div class="line">
<label for="date-of-birth">Date of Birth</label>
<input type="date" id="date-of-birth" @bind="NewUser.DateOfBirth" />
</div>
<Button Text="Add User" OnClick="Save" />
</form>
</div>
}
</Authorized>
</AuthorizeView>
@code {
private async void Save()
{
IsLoading = true;
StateHasChanged();
if (!AreFormValuesValid()) return;
NewUser.Id = 0;
NewUser.Password = NewUser.Name;
NewUser.Role = roleService.Get("Participant");
NewUser.Gender = Gender == "Male" ?
Enumerations.Gender.Male : Enumerations.Gender.Female;
if (await userService.AddOrUpdate(NewUser))
{
js.InvokeVoidAsync("alert", "User Added Successfully");
NewUser = new User();
Gender = "";
StateHasChanged();
} else
{
js.InvokeVoidAsync("alert", "Couldn't Save User");
}
IsLoading = false;
StateHasChanged();
}
加载文本出现在警告之后,但我希望加载文本在我单击按钮时出现。我如何改变我的代码来实现这一点。
我试了很多方法,都卡了好几个小时了,有谁能帮我吗?(这是一个Blazor服务器应用程序项目)
1条答案
按热度按时间vdzxcuhz1#
更新UI只能在
await
期间进行。如果消息只出现在警报之后,那么userService.AddOrUpdate()
并不是真正的异步。添加延迟以更新屏幕: