TLDR; 就像字符串/文本框绑定在输入控件上正常工作一样,但布尔属性支持的复选框绑定不起作用。我知道复选框值的绑定需要使用'checked'属性而不是'value'属性,但是Blazor应该在不同的控件类型之间进行处理。
我正在使用RC1做一些Blazor的工作(服务器端应用程序),似乎无法获得绑定到输入复选框控件的布尔值。我相信所使用的语法是正确的(请参阅下文)。作为一个简单的测试,我创建了一个新项目,并使用下面的示例代码简单地替换了index.razor页面。运行它时,请注意:
@page "/"
<div class="form-group">
<label for="last-name">Textbox Binding Test</label>
<input @bind="TestString" type="text" class="form-control" id="last-name" placeholder="Enter Last Name" />
</div>
<div class="form-group">
<label for="send-email-updates">Checkbox Binding Test</label>
<input type="checkbox" bind="@TestBool" id="send-email-updates" />
</div>
@code {
private bool _testBool = true;
protected bool TestBool
{
get { return _testBool; }
set
{
_testBool = value;
System.Diagnostics.Debug.WriteLine($"Value of {nameof(TestBool)} = {value}");
}
}
private string _testString = "Test Value";
protected string TestString
{
get { return _testString; }
set
{
_testString = value;
System.Diagnostics.Debug.WriteLine($"Value of {nameof(TestString)} = {value}");
}
}
}
无论将属性设置为公共属性,使用自动属性(无私有变量)还是删除控件名称/ id属性值,都观察到此行为。无论我在页面上使用@code指令还是分离出从ComponentBase继承的视图模型,这似乎都会发生。
最重要的是,当用户提交表单时,我能够获得基于文本的值,但是所有的布尔属性似乎都保持了首次初始化时的状态。
答案 0 :(得分:4)
当您同时看到两个控件时:
viaNonEmpty :: (NonEmpty a -> b) -> ([a] -> Maybe b)
很明显,您正在混合使用<input @bind="TestString" type="text" class="form-control" id="last-name" placeholder="Enter Last Name" />
<input bind="@TestBool" type="checkbox" id="send-email-updates" />
和bind
表示法,可能来自旧的Blazor版本。
这在rc1中有效:
@bind
但总的来说,我会建议使用<input type="checkbox" @bind="TestBool" id="send-email-updates" />
和相关标签:
<EditForm>