如何在viewmodel中创建可选的是/否单选按钮

假设我有很长的forms,用户可以输入许多不同的可选值。

其中一个可选值是布尔值。 根据用户输入,我需要在我的数据库中执行以下操作:

  • 如果“是”,则在数据库中添加“1”
  • 如果为“否”,则在数据库中添加“0”
  • 如果输入non,则在数据库中添加“null”

但是,我能找到的最正常的viewmodel / razor代码如下:

@Html.LabelFor(m => m.FurnitureIsIncluded) @Html.RadioButtonFor(model => model.FurnitureIsIncluded, true) Ja 

这里我的值将为false,作为布尔值的默认值。

在MVC中解决这个问题的方法是什么?

在视图模型中为FurnitureIsIncluded使用可空的bool

 @Html.RadioButtonFor(m => m.FurnitureIsIncluded, "true")Yes @Html.RadioButtonFor(m => m.FurnitureIsIncluded, "false")No @Html.RadioButtonFor(m => m.FurnitureIsIncluded, "", Model.FurnitureIsIncluded.HasValue ? null : new { @checked = "checked" })Cant decide 

然后,这将根据选择回发truefalsenull 。 然后,您需要测试true / false以将值保存为“1”或“0”