Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind a model to Radio Button in ASP.NET MVC4?

I have a model

 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; }

 }

create a radio button on my view

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


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

user can select man or woman radio buttons on register form, but why always WomanSelected and ManSelected are both false after click submit form button in my action?

like image 323
motevalizadeh Avatar asked Jun 30 '13 10:06

motevalizadeh


1 Answers

You should be binding your radio buttons in MVC via RadioButtonFor i.e.

@Html.RadioButtonFor(m => m.ManSelected, m.Man);
@Html.RadioButtonFor(m => m.WomanSelected, m.Woman);
like image 62
James Avatar answered Sep 29 '22 04:09

James