The goal here is to have a checkbox bound to a bool variable of an object. Now when we check the box it should give a confirmation pop up and if I select ‘yes’ it should go ahead with the procedure, but if I select ‘no’ then it should come back to the original state. So, for the demo I implemented a confirm box and there I am checking the condition.
Razor file:
<InputCheckbox @bind-Value="@product.IsAssociated" @oninput="(e)=>AssociateProducts(e,product)"/>
Code:
public async void AssociateProducts(ChangeEventArgs e,Product product)
{
bool confirmed = await JSRuntime.InvokeAsync<bool>("confirm", "Are you sure?");
if (confirmed)
{
//normal procedure
}
else
{
//this code isn't changing the state
product.IsAssociated = false;
StateHasChanged();
}
}
So when we give ‘No’ as our answer, this code executes:
else
{
//this code isn't changing the state
product.IsAssociated = false;
StateHasChanged();
}
I want that the checkbox to be unchecked after this.
This doesn’t change the state of our product and it is ‘TRUE’ only when I printed it and checked.
How can I achieve this?
2
Answers
I just add
EditForm
and it works successfully.Demo
I hope it is what you expect.
This is my second answer… This is how you have to code and use logics
Either use the
change
event or theinput
event, but not both. When you do this:You are using two events while you can and should use a single event:
change
Do use
async Task
instead ofasync void
Most importantly, your logics is faulty: When you run the app for the first time and
product.IsAssociated
is false. The user checks the checkbox, he clicks OK as a geture of confirmation. Suppose he decided after this action to cancel his previous selection. In order to do that he should click on the checked checkbox in order to undo the previous action. Your code does not do that, and does not take into account, clicking on the "Cancel" button.