這里的目標是讓復選框系結到物件的 bool 變數。現在,當我們選中該框時,它應該會彈出一個確認訊息,如果我選擇“是”,它應該繼續執行該程序,但如果我選擇“否”,那么它應該回到原始狀態。因此,對于演示,我實作了一個確認框,并在那里檢查條件。
剃須刀檔案:
<InputCheckbox @bind-Value="@product.IsAssociated" @oninput="(e)=>AssociateProducts(e,product)"/>
代碼:
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();
}
}
因此,當我們給出“否”作為我們的答案時,此代碼將執行:
else
{
//this code isn't changing the state
product.IsAssociated = false;
StateHasChanged();
}
我希望在此之后取消選中該復選框。這不會改變我們產品的狀態,只有當我列印并檢查時它才是“真”。
我怎樣才能做到這一點?
uj5u.com熱心網友回復:
這是我的第二個答案......這就是你必須如何編碼和使用邏輯
使用change事件或input事件,但不能同時使用。當你這樣做時:
`@bind-Value="@product.IsAssociated" @oninput="
(e)=>AssociateProducts(e,product)"`
您正在使用兩個事件,而您可以并且應該使用一個事件:change
使用async Task而不是async void
最重要的是,你的邏輯是錯誤的:當你第一次運行應用程式時,product.IsAssociated它是錯誤的。用戶選中復選框,然后單擊 OK 作為確認。假設他在這個動作之后決定取消他之前的選擇。為此,他應單擊選中的復選框以撤消先前的操作。您的代碼沒有這樣做,也沒有考慮到單擊“取消”按鈕。
@page "/"
@inject IJSRuntime JSRuntime
<EditForm Model="product">
<InputCheckbox ValueExpression="@( () => product.IsAssociated )"
Value="@product.IsAssociated"
ValueChanged="@( (bool args) => AssociateProducts(args, product) )"/>
</EditForm>
<div>product.IsAssociated: @product.IsAssociated</div>
@code {
private Product product = new Product { ID = 1, Name = "Product1", IsAssociated = false };
public async Task AssociateProducts(bool args, Product product)
{
bool confirmed = await JSRuntime.InvokeAsync<bool>( "confirm", new [] { "Are you sure?" });
if (confirmed && !product.IsAssociated)
{
product.IsAssociated = true;
}
else if(confirmed && product.IsAssociated)
{
product.IsAssociated = false;
}
}
public class Product
{
public int ID { get; set; }
public string Name { get; set; }
public bool IsAssociated { get; set; }
}
}
uj5u.com熱心網友回復:
我只是添加EditForm并成功運行。
@page "/"
@inject IJSRuntime JsRuntime
<PageTitle>Index</PageTitle>
<EditForm Model="@product">
<InputCheckbox @bind-Value="@product.IsAssociated" @oninput="(e)=>AssociateProducts(e,product)"/>
</EditForm>
@code{
public Product product { get; set; } = new Product();
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();
}
}
}
演示

我希望這是你所期望的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/483045.html
