【问题标题】:MVC radio buttons for 3 bool properties3 个布尔属性的 MVC 单选按钮
【发布时间】:2021-10-23 20:21:23
【问题描述】:

我有一个具有 3 个布尔属性的模型:

public class ViewModel {
  public bool A { get; set; }
  public bool B { get; set; }
  public bool C { get; set; }
}

如果我是对的,默认情况下它们都是false。 我想要 3 个单选按钮,所以其中只有一个可以是 true

<input asp-for="A" name="type" type="radio" value="true" id="A"/>
<input asp-for="B" name="type" type="radio" value="true" id="B"/>
<input asp-for="C" name="type" type="radio" value="true" id="C"/>

但是当我从 3 个中选择一个并提交我的表单时,视图模型中的每个值都将是 false

我该如何解决这个问题?最主要的是我只想使用 3 个单选按钮。

【问题讨论】:

  • 您只是向我们展示了属性的声明及其对应的 HTML,而不是您如何获取值。如果您期望“真”但得到假,那么您不是从输入元素中获取值,而是从属性中获取它们的默认值,除非另有声明,否则布尔值始终为“假”。

标签: c# asp.net-mvc radio-button


【解决方案1】:

单选按钮的工作方式与复选框不同。如果是单选按钮,则从一组单选按钮中选择的单选按钮的值将被发送回操作。

要对单选按钮进行分组 - html 元素的 name 属性必须相同(我可以在您的 html 中看到)。现在您只需要一个变量来捕获所选单选按钮的value。您必须为单选按钮设置 value 属性。

HTML:

<input asp-for="A" name="type" type="radio" value="A" id="A"/>
<input asp-for="B" name="type" type="radio" value="B" id="B"/>
<input asp-for="C" name="type" type="radio" value="C" id="C"/>

那么在行动中:

public class ViewModel {
  public string type { get; set; }
}

type 属性的值将在服务器端的type 变量中可用。例如“A”或“B”或“C”但不是真/假。

【讨论】:

    猜你喜欢
    • 2011-07-24
    • 2016-11-01
    • 2011-08-24
    • 2012-05-18
    • 1970-01-01
    • 2011-02-16
    • 1970-01-01
    • 2014-01-20
    • 1970-01-01
    相关资源
    最近更新 更多