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

5
我有一个模型。
 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都为false呢?


请使用 Html.RadioButtonFor ,像这样:Html.RadioButtonFor(m => m.ManIsSelected, Model.ManId)。但是,你可以解释一下 Model.ManModel.Sex.Man 是什么吗? - Dai
抱歉,我之前编辑成了 Model.man,这是个错误。我已经更改为 @Html.RadioButtonFor(m=>m.ManSelected,Model.ManId, new { @class = "radio" }) 但它并没有起作用。 - motevalizadeh
4
SexModel - 最好的类名,加一分。 - James
1个回答

5

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

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

我的操作是 [HttpPost],public ActionResult Index(SexModel sexModel) 这样写对吗?使用你的解决方案还没生效,我有点困惑 :) - motevalizadeh
@motevallizadeh,看起来对我没问题。你是否也有 public ActionResult Index() { return View(new SexModel()); }?请把你的控制器发布出来... - James
是的,我有它。公共动作结果索引() { SexModel ff = new SexModel(); 返回视图(ff); } - motevalizadeh

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