将模型绑定到ASP.NET MVC4中的单选按钮?

时间:2013-06-30 10:53:21

标签: asp.net-mvc-4

我有一个模特

 public class SexModel
 {
    public SexModel()
    {

        this.Man = "Man";
        this.Woman = "Woman";
        this.ManId = 1;
        this.WomanId = 2; 
        this.WomanSelected = this.ManSelected = false;
    }

    public bool ManSelected { get; set; }
    public bool WomanSelected { get; set; }
    public string Man { get; set; }
    public string Woman { get; set; }
    public int ManId { get; set; }
    public int WomanId { get; set; }

 }

在我的视图上创建一个单选按钮

 @Html.RadioButton(Model.Man,  Model.ManId, Model.ManIsSelected, 
                   new { @id = Model.ManId})


 @Html.RadioButton(Model.Man, Model.WomanId, Model.WomanSelected,
                   new { @id = Model.WomanId })

用户可以在注册表单上选择男人或女人单选按钮,但为什么在我的操作中点击提交表单按钮后,WomanSelected和ManSelected总是都是假的?

1 个答案:

答案 0 :(得分:5)

您应该通过RadioButtonFor绑定MVC中的单选按钮,例如

@Html.RadioButtonFor(m => m.ManSelected, m.Man);
@Html.RadioButtonFor(m => m.WomanSelected, m.Woman);