UI 元素仅在焦点从原始位置移开时更新 button/input

UI Elements only update when focus is moved away from original button/input

我遇到一个问题,我按下一个按钮,服务器会给出响应,但是 UI 不会更新以显示我为它设置的响应,直到我开始与某些东西交互别的。似乎无法弄清楚是什么原因造成的。一直在检查代码,根据 UI 布局进行更改,但似乎没有任何效果。我这里有一个 gif 可以更好地演示。我试过使用 StateHasChanged 但这似乎也不起作用

剃刀页面

<EditForm Model="@AssignUser" OnValidSubmit="@AddUserToProject">

@*    <DataAnnotationsValidator />*@
<div class="form-group">
    <label class="custom-control-label"> Assign Users </label>
    <InputText placeholder="Username" id="inlineFormInputGroup" type="email" @bind-Value="@AssignUser.UserName" class="form-control" />

    <button type="submit" class="btn btn-success">Add</button>
</div>
</EditForm>
//display messages depending on outcome
@if (userNotFoundError == true)
{
    <div class="alert alert-danger" role="alert">
        User could not be found
    </div>
}

@if (userExistsAlready == true)
{
    <div class="alert alert-danger" role="alert">
        User is already on the project
    </div>
}

将用户添加到项目功能

private bool userNotFoundError = false;
private bool userExistsAlready = false;
private async void AddUserToProject()
{
    try
    {
        var response = await Http.PutAsJsonAsync($"Projects/add/User/{AssignUser.UserName}/{projectItem.ProjectId}", AssignUser);

        // Attempt add adding someone who is already on the project?
        if (response.StatusCode == HttpStatusCode.Forbidden)
        {
            StateHasChanged();

            if (userNotFoundError == true)
            {
                userNotFoundError = false;
            }
            userExistsAlready = true;

            
        }
// Attempt at adding someone who does not exist as a user?
        else if (response.StatusCode == HttpStatusCode.BadRequest)
        {
            StateHasChanged();

            if (userExistsAlready == true)
            {
                userExistsAlready = false;
            }
            userNotFoundError = true;
        }
        else
        {
            var content = await response.Content.ReadAsStringAsync();
            var userobject = JsonConvert.DeserializeObject<ApplicationUser>(content);
            response.EnsureSuccessStatusCode();
            Navigation.NavigateTo("/projects");
            userNotFoundError = false;
            userExistsAlready = false;
            StateHasChanged();
        }

    }
    catch (Exception e)
    {
        userNotFoundError = true;
    }
}

在控制器中添加用户功能

[HttpPut("add/User/{userName}/{projID}")]
public async Task<IActionResult> AddUserToProject(string userName, Guid projID)
{

    var project = _context.Projects.Include(u => u.AssignedUsersToProject).FirstOrDefault(p => p.ProjectId.ToString().Equals(projID.ToString()));

    try
    {
        var user = _context.Users.First(u => u.UserName.Equals(userName));

        if (!project.AssignedUsersToProject.Any(u => u.UserName.Equals(user.UserName))) { 
            project.AssignedUsersToProject.Add(user);                    
        } else
        {
            return Forbid();
        }
    }
    catch (InvalidOperationException)
    {
        return BadRequest();
    }

    try
    {
        await _context.SaveChangesAsync();
    }
    catch (DbUpdateConcurrencyException)
    {
        if (!ProjectExists(projID))
        {
            return NotFound();
        }
        else
        {
            throw;
        }
    }

    return NoContent();
}

改变

private async void AddUserToProject()

private async Task AddUserToProject()

它应该可以工作。

然后您还可以删除所有这些 StateHasChanged() 调用,它们不再有任何作用。

Blazor 不知道 async void 何时完成。当您使用 async Task 方法时,Blazor 将在该方法完成时自动重新呈现您的 UI。

但我怀疑显示错误还有另一个问题。对于大多数分支,StateHasChanged() 调用应该有 'repaired' async void