MVC 单选按钮选中一个

MVC Radio button selected one

出于某种原因,我有如下单选按钮,即使第一个被选中,最后一个总是显示在表单页面上被选中。为什么 ?我该如何解决这个问题?

@Html.RadioButtonFor(model => model.IsSatisFied, Satisfaction.Not, new { @checked = "true" }) 
@Html.RadioButtonFor(model => model.IsSatisFied, Satisfaction.Maybe, new { @checked = "false" })  
@Html.RadioButtonFor(model => model.IsSatisFied, Satisfaction.Yes, new { @checked = "false" })  

您使用的格式不正确 HTML。将某些内容标记为已检查的正确方法是

{ @checked = "checked" }

并且对于未选中的单选按钮根本不包含选中的属性。

不要设置 checked 属性。 @checked = "true"@checked = "false"(以及 checkedchecked="checked"checked="anything")都设置了 checked 属性。当读取 DOM 时,检查第一个,然后检查第二个,最后检查最后一个。

如果 属性 的值 IsSatisFiedSatisfaction.Maybe 那么第二个单选按钮将被选中(这就是模型绑定的工作原理)

HTML specification 说:

When any of the following phenomena occur, if the element's checkedness state is true after the occurrence, the checkedness state of all the other elements in the same radio button group must be set to false:

  • The element's checkedness state is set to true (for whatever reason).
  • The element's name attribute is set, changed, or removed.
  • The element's form owner changes.

因此,随着 HTML 被解析到页面下方,如果多个收音机是 checked,那么最后一个将始终被选中。因此,您只想通过设置 checked="checked":

来设置一个选中的属性
@Html.RadioButtonFor(
    model => model.IsSatisFied, 
    Satisfaction.Not, 
    new { @checked = "checked" }) 
@Html.RadioButtonFor(model => model.IsSatisFied, Satisfaction.Maybe)  
@Html.RadioButtonFor(model => model.IsSatisFied, Satisfaction.Yes)