.NET Core Blazor: 如何在复选框被选中时获取其值?

49

我正在尝试使用Blazor框架获取复选框的值,如果它被选中,但是到目前为止我还没有找到任何方法。当我将绑定放在复选框中时,它总是被选中。我无法弄清如何获取选中的值。

这是我的代码:

<input type="checkbox" id="addition" name="math" value="add" bind="@name" />
<label for="addition">Addition</label>
8个回答

40

将复选框的值绑定到布尔值。

在您的@Code中,bool checkedValue = false; // 或true,根据您的用例

在您的HTML中:

<input type="checkbox" checked @bind="checkedValue">

checkedValue的值将与您的复选框的值相同。


3
由于“checked attribute is set twice”错误,它无法编译。仅供参考。 - ˈvɔlə
2
checked parameter seems to be set by default. So in this case you can just delete the checked attribute. For unchecked checkbox use: <input type="checkbox" @bind="checkedValue" unchecked> - ssamko

39
@page "/registration"

    @foreach (var club in ClubList())
    {
        <input type="checkbox" @onchange="eventArgs => { CheckboxClicked(club, eventArgs.Value); }" />@club<br />
    }

@functions {

    public List<string> ClubMember { get; set; } = new List<string>();
    void CheckboxClicked(string clubID, object checkedValue)
    {
        if ((bool)checkedValue)
        {
            if (!ClubMember.Contains(clubID))
            {
                ClubMember.Add(clubID);
            }
        }
        else
        {
            if (ClubMember.Contains(clubID))
            {
                ClubMember.Remove(clubID);
            }
        }
    }

    public List<String> ClubList()
    {
        // fetch from API or...
        List<String> c = new List<String>();
        c.Add("Clube01");
        c.Add("Clube02");
        return c;
    }

}

1
直到我也使用了checked属性,这才对我起作用——请注意,checked仍然可以绑定到一个函数,例如checked="@(HasClubMember(clubID))" - Slate
我的猜测是 c.Add("Clube01"); 是一个笔误(应该是 Clube 而不是 Club),而 c.Add("Clube02"); 则是复制粘贴时传播了这个错误 :) - MikeT
@MichaelTranchida 这不是打字错误 :) 它只是用另一种语言(葡萄牙语)写的“club”单词。 - Manuel Alves

13

我认为其他答案都没有解决我所寻找的两个问题:

  1. 将复选框的初始值设置为可以是true或false的变量
  2. 让我响应复选框的onchange事件,以便在选中/取消选中复选框时将更改发送回服务器或执行其他操作。

我的解决方案实现了这两个功能,但需要重复使用<input>标签来区分选中和未选中的版本。

Razor文件如下:

 @if (Approved)
 {
    <input type="checkbox" checked @onchange="@(async (e) => 
              await ToggleApprovedAsync(false))" />
 }
 else
 {
     <input type="checkbox"  @onchange="@(async (e) => 
              await ToggleApprovedAsync(true))" />
 }


@code {

    bool Approved;

    override async Task OnInitializedAsync()
    {
        Approved = await HttpClient.GetJsonAsync<bool>("../api/IsApproved");
    }

    async Task ToggleApprovedAsync(bool approved)
    {
        Console.WriteLine("Toggle Approved " + approved );
        if (approved)
        {
            await HttpClient.PostJsonAsync<bool>($"../api/Approve", null);
            Approved = true;
        }
        else
        {
            await HttpClient.PostJsonAsync<bool>($"../api/Disapprove", null);
            Approved = false;
        }
    }

}

1
我不知道为什么人们会把事情搞得这么复杂... 我更喜欢简单的布尔表达式 ("@((myitem.checked) ? "checked" : "")并且@onchange="eventArgs => { ApprovedToggle((bool)eventArgs.Value, item.Isapproved); }"此外,在按钮事件中做一些工作是不好的。按钮会等待直到... - Tim Davis
1
@TimDavis 很好的建议,只是在 Blazor 中你的 "checked" 对我没有起作用。我使用 checked="@myItem.checked" 就可以了。任何 Razor 表达式评估为 false 的情况都不会呈现 "checked" 属性,所以浏览器不会混淆。 - Eugene

8

移除value属性:

<input type="checkbox" id="addition" name="math" bind="@name" />

将此属性添加到@function块或从BlazorComponent派生的类中:
public bool name {get;set;}

现在你的复选框的值已经绑定到name属性,并且您可以访问该属性,其中包含复选框的值,以检索复选框的值,就像您访问其他属性一样。希望这可以帮助您...

5
你可以尝试这样做:
<input type="checkbox" @bind-value="YourConditionTypeOfBool" checked="@(YourConditionTypeOfBool?"checked":null)"/>&nbsp; Is True
<span>My condition is @(YourConditionTypeOfBool?"True":"False")</span>

在代码后台,您需要定义 YourConditionTypeOfBool 变量,例如:
@code{
     bool YourConditionTypeOfBool = true;
}

checked="@(YourConditionTypeOfBool?"checked":null)" .... 很好,感谢伙伴。 - FarrukhMalik

5

你需要移除value="add"部分。

并确保name是布尔型。

编辑:完整示例

@page "/test2"

<input type="checkbox" bind="@boolvalue" /><br/>
Boolvalue: @boolvalue<br/>
<button onclick="@toggle">toggle</button>

@functions
{

   public bool boolvalue { get; set; }

   void toggle()
   {
       boolvalue = !boolvalue;
   }
}

哦,我明白了。但是有没有办法可以获取它的值?因为当我删除值部分时,就没有值可获取了。 - jorjj
你正在绑定到 @name,因此它将保存该值。 - Flores
它将保留该值,直到我设置某些内容。我的意思是,我如何从那里获取静态值? - jorjj
1
不确定您的意思。但我已经提供了一个包含我能想到的所有内容的示例。希望这有所帮助。 - Flores

3
您可以在代码后台创建一个属性将该值绑定到,然后使用bind-value属性。
属性定义应该类似于: public bool name {get;set;} 然后您可以使用@bind-value属性: <input type="checkbox" id="name" @bind-value=name class="form-check-input"> 或者您可以使用内置的InputCheckbox组件: <InputCheckbox @bind-Value="starship.IsValidatedDesign" />

https://learn.microsoft.com/en-us/aspnet/core/blazor/forms-validation?view=aspnetcore-5.0#built-in-forms-components

忘记提到 InputCheckbox 必须放在 EditForm 内。

0

我来到这里主要是想再次检查语法,因为我有点脑抽,而且这仍然是谷歌的首选结果。我的特定情况类似于Mike的情况,我需要复选框的更改事件来驱动另一个组件是否可见。

我的解决方案使用了Flores的建议,以某种方式整理了Mike的想法。这只是对话框的基本结构,使用了我的机制:

<div class="modal fade show" id="newsApprove" style="display:block;background-color:rgba(10,10,10,8);" aria-modal="true" role="dialog">
    <div class="modal-dialog" style="vertical-align:central">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Dates Active</h4>
                <button type="button" class="close" @onclick="@Cancel">&times;</button>
            </div>
            <div class="modal-body">
                <div class="input-group mb-3">
                    <div class="input-group-text">
                        <input type="checkbox" aria-label="Active From Now?" id="activeNow" @bind-value="isChecked" />
                    </div>
                    <label class="form-check-label" for="activeNow">Render This Active Immediately?</label>
                </div>
                @if (!isChecked)
                {
                    <div>
                        <SfDateTimePicker TValue="DateTime" Min="DateTime.Now" @bind-Value="activeFrom"></SfDateTimePicker>
                    </div>
                }
                <SfDateTimePicker TValue="DateTime" Min="DateTime.Now" @bind-Value="activeTo"></SfDateTimePicker>
            </div>
            <div class="modal-footer">
                <button type="submit" class="btn-primary" @onclick="@Save">Approve</button>
                <button type="button" class="btn-secondary" @onclick="@Cancel">Cancel</button>
            </div>
        </div>
    </div>
</div>


@code {
    public DateTime activeTo { get; set; }
    public DateTime activeFrom { get; set; }

    private bool isChecked { get; set; } = true;

}

从那里开始,如果您需要在复选框更改事件触发时进行更多处理,则可以添加一个方法来执行相关处理并相应地切换isChecked的值。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接