MVC单选按钮被选中1

问题描述:

由于某些原因,我有单选按钮,即使选中了第一个按钮,总是最后一个出现在表单页面上。为什么?我怎样才能解决这个问题?MVC单选按钮被选中1

@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" }) 

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

如果属性格式的值是IsSatisFiedSatisfaction.Maybe然后第二个单选按钮将被选中(这是如何模型结合的作品)

+0

怎样一个动态的检查属性添加到相应的单选按钮?假设选项列表是动态构建的。 – Kevin 2017-06-05 14:37:30

+0

@凯文,你需要提出一个新的问题与相关的细节 – 2017-06-05 22:01:03

您使用格式不正确的HTML。将标记为选中状态的正确方法是

{ @checked = "checked" } 

并且对于未选中的单选按钮不包括checked属性。

HTML specification说:

当下列任一现象时有发生, 如果发生后元素的检查状态为真,则同一单选按钮组中所有其他元素的检查状态必须设置为假

  • 元素的检查状态设置为true(无论什么原因)。
  • 元素的名称属性被设置,更改或删除。
  • 元素的表单所有者发生变化。

因此,作为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)