数据未加载在OnAfterRenderAsync()Blazor服务器中



这里我有blazor服务器应用程序,我正在尝试删除角色,删除后我想再次加载角色列表并显示删除的消息。

但问题是,删除角色后会显示删除消息,但角色列表不会再次加载

以下是我所做的

角色列表.razor

@foreach (var item in roleList)
{
<tr>
<td>@item.Name</td>
<td>
<a href="/admin/editrole/@item.Id" class="btn btn-outline-primary"><i class="far fa-edit"></i> Edit</a>
<button @onclick="()=>DeleteRole(item.Id)" class="btn btn-outline-danger"><i class="far fa-trash-alt"></i> Delete</button>
</td>
</tr>
}

protected async override Task OnAfterRenderAsync(bool firstRender)
{
await jSRuntime.InvokeAsync<string>("AddDataTables", new object[] { "#example" });
if (MessageStaus.MessageId == 1)
{
toastService.ShowSuccess("Role successfully created");
MessageStaus.MessageId = 0;
}
else if(MessageStaus.MessageId == 2)
{
toastService.ShowSuccess("Role successfully edited");
MessageStaus.MessageId = 0;
}
else if(MessageStaus.MessageId == 3)
{
toastService.ShowSuccess("Role successfully deleted");
roleList = mainService.GetAllRoles();
StateHasChanged();
MessageStaus.MessageId = 0;
}          
await base.OnAfterRenderAsync(firstRender);
}

protected override void OnInitialized()
{
roleList = mainService.GetAllRoles();
base.OnInitialized();
}

public async Task DeleteRole(string roleId)
{
var role = await roleManager.FindByIdAsync(roleId);
bool confirmed = await jSRuntime.InvokeAsync<bool>("confirm", "Are you sure?");
if (confirmed)
{
var result = await roleManager.DeleteAsync(role);       
if (result.Succeeded)
{
MessageStaus.MessageId = 3;
}
}
}

您正在尝试在OnAfterRenderAsync中重新加载roleList。方法的名称应该有点泄露。AFTERRENDER=组件已经渲染,只有在重新渲染组件时,任何更改才会进入UI。

将您的roleList更新添加到DeleteRole。在DeleteRole完成之前,组件不会重新渲染。

public async Task DeleteRole(string roleId)
{
var role = await roleManager.FindByIdAsync(roleId);
bool confirmed = await jSRuntime.InvokeAsync<bool>("confirm", "Are you sure?");
if (confirmed)
{
var result = await roleManager.DeleteAsync(role);       
if (result.Succeeded)
{
MessageStaus.MessageId = 3;
// Added here to update roleList after it changes
roleList = mainService.GetAllRoles();
}
}
}

相关内容

  • 没有找到相关文章

最新更新