Actual Behavior: The SelectedRole does not reflect the new selection, and the saved role remains as the initially loaded role.
How can I ensure that the InputSelect properly updates the SelectedRole variable?
Try to set a break point in the OnInitializedAsync
method, you will find that after submitting the form, this method will execute first and then the SaveChanges
method, so it will change the selected value to the default value.
To solve this issue, you can check whether the SelectedRole
is null or not in the OnInitializedAsync
method, and then set the default value. Code like this:
protected override async Task OnInitializedAsync()
{
if (Id is not null)
{
User = await UserManager.FindByIdAsync(Id);
if (User is null)
{
DebugMessage = "Usuário não encontrado.";
NavigationManager.NavigateTo("/notfound");
return;
}
AllRoles = RoleManager.Roles.ToList();
var roles = await UserManager.GetRolesAsync(User);
//if the SelectRole is null, set the default value.
if (SelectedRole is null)
SelectedRole = roles.FirstOrDefault() ?? "-1";
}
}
Besides, since you will receive the data from the form. I think you'd better to add the [SupplyParameterFromForm]
attribute for the User
and SelectedRole
, after modified the code should like this:
[SupplyParameterFromForm]
private ApplicationUser? User { get; set; } = new();
[SupplyParameterFromForm]
private string? SelectedRole { get; set; }
After that in the SaveChanges method, you can see the selected value.