First things first, getting a boolean value is usually a checkbox, so you can try that first.
<EditForm Model="@Foo">
Type: @Foo.Bar.GetType()
<br />
Value: @Foo.Bar
<br /><br />
<InputCheckbox @bind-Value="@Foo.Bar">I understand</InputCheckbox>
</EditForm>
@code{
MyClass Foo { get; set; } = new MyClass();
public class MyClass
{
public bool Bar { get; set; } = true;
}
}
If you do have to use radio buttons, read on.
I think that this should, ideally, work with real bool values but it seems it does not, here is a repro (perhaps you could log it with MS in their repo) - initially it seems to parse OK, but changing the value throws that it can't parse from a string. This indicates to me that they only support string and int for the radio button groups.
<EditForm Model="@Foo">
Type: @Foo.Bar.GetType()
<br />
Value: @Foo.Bar
<br /><br />
<InputRadioGroup Name="FooBar" @bind-Value="@Foo.Bar">
<InputRadio Name="FooBar" Value="@true" />Yes<br>
<InputRadio Name="FooBar" Value="@false" />No<br>
</InputRadioGroup>
</EditForm>
@code{
MyClass Foo { get; set; } = new MyClass();
public class MyClass
{
public bool Bar { get; set; } = true;
}
}
Solutions:
- Use an enum if you can (it is basically an integer, which is why it works)
- Use a helper field that can be parsed to the desired bool value (example below)
For the helper field to work out, you need strings that you can parse and you might need them as variables in the view-model, because just setting Value="@true" or Value="true" will actually either try to look for a field, or use the boolean value, while the HTML element matches as a string. A bit of a catch 22 with the syntax.
<EditForm Model="@Foo">
Type: @Foo.Bar.GetType()
<br />
Value: @Foo.Bar
<br />
String Value @Foo.BarString
<br /><br />
<InputRadioGroup Name="FooBar" @bind-Value="@Foo.BarString">
<InputRadio Name="FooBar" Value="@trueVal" />Yes<br>
<InputRadio Name="FooBar" Value="@falseVal" />No<br>
</InputRadioGroup>
</EditForm>
@code{
string trueVal = "true";
string falseVal = "false";
MyClass Foo { get; set; } = new MyClass();
public class MyClass
{
public string BarString { get; set; } = "true";
public bool Bar { get { return bool.Parse(BarString); } set { BarString = value.ToString().ToLowerInvariant(); } }
}
}