jor*_*rjj 5 html c# .net-core blazor
我正在尝试获取使用Blazor框架进行检查的复选框的值,但到目前为止我找不到任何方法。当我将绑定放在复选框中时,始终会选中它。我不知道如何获得检查的值。
这是我的代码:
<input type="checkbox" id="addition" name="math" value="add" bind="@name" />
<label for="addition">Addition</label>
Run Code Online (Sandbox Code Playgroud)
小智 24
将复选框值绑定到布尔值。
在你的@Code 中, bool checkedValue = false; // 或 true 如果它适合您的用例
在您的 HTML 中:
<input type="checkbox" checked @bind="checkedValue">
Run Code Online (Sandbox Code Playgroud)
checkedValue 的值将与您的复选框具有相同的值。
我不认为其他任何答案都符合我的要求:
我的解决方案完成了这两件事,但需要为已检查和未检查的版本重复标记。
剃刀文件如下所示:
@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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
删除 value 属性:
<input type="checkbox" id="addition" name="math" bind="@name" />
Run Code Online (Sandbox Code Playgroud)
将此属性添加到 @function 块或从 BlazorCoponent 派生的类:
public bool name {get;set;}
Run Code Online (Sandbox Code Playgroud)
现在,您的复选框的值绑定到 name 属性,您可以访问此属性,其中包含复选框的值,以检索复选框的值,就像访问其他属性一样。
希望这可以帮助...
小智 6
你可以试试这个:
<input type="checkbox" @bind-value="YourConditionTypeOfBool" checked="@(YourConditionTypeOfBool?"checked":null)"/> Is True
<span>My condition is @(YourConditionTypeOfBool?"True":"False")</span>
Run Code Online (Sandbox Code Playgroud)
在后面的代码中,您需要定义 YourConditionTypeOfBool 变量,例如:
@code{
bool YourConditionTypeOfBool = true;
}
Run Code Online (Sandbox Code Playgroud)
您必须删除该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;
}
}
Run Code Online (Sandbox Code Playgroud)
@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;
}
}
Run Code Online (Sandbox Code Playgroud)