@Html.RadioButtonFor 默认为未选中状态

8
在ASP.NET MVC4的Razor视图中,如何确保所有的单选按钮都默认不选中?即使在下面的代码中没有声明要选中其中的一个,MVC似乎还是会为我选中一个。
@Html.RadioButtonFor(model => model.test, true, new { id = "radio_test_True"}) Yes
@Html.RadioButtonFor(model => model.test, false, new { id = "radio_test_False"}) No

谢谢

1个回答

9
在您的控制器或模型构造函数中将Model.test设置为null,并确保其可为空。一个bool必须是true或false,null表示两者都未被选中。
public class WhateverTheModelIs
{
    public bool? test { get; set; }

    public WhateverTheModelIs()
    {
        test = null;
    }
}

注意:将值设置为 null 是多余的,因为它是默认值。我想举例明确一下。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接