2013-06-30 33 views
5

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

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都是点击后假在我的动作中提交表单按钮?

+0

使用具有约束力的单选按钮MVC'Html.RadioButtonFor'代替,就像这样:'Html.RadioButtonFor(M => m.ManIsSelected,Model.ManId)' 。虽然你能解释一下'Model.Man'和'Model.Sex.Man'是什么? – Dai

+0

对不起,我编辑Model.man这是一个错误。我将它改为@ Html.RadioButtonFor(m => m.ManSelected,Model.ManId,new {@class =“radio”})但它没有工作 – motevalizadeh

+4

' SexModel' - 最好的类名尚未+1 – James

回答

5

你应该通过RadioButtonFor

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

我的动作是[HttpPost] public ActionResult Index(SexModel sexModel)是否正确?与您的解决方案不工作,但我很困惑:) – motevalizadeh

+0

@motevallizadeh yep看起来对我好。你也有'公众的ActionResult指数(){返回视图(新的SexModel()); }'?发布你的控制器... – James

+0

是的,我有它公开的ActionResult指数() { SexModel ff = new SexModel(); return View(ff); } – motevalizadeh