How can I bind a radio button with model data in ASP.Net MVC?

If I understood correctly you should change your Student model in order to have the property “Sex” as an integer and then you should have another property called “SexList” where you populate the list. This change will allow you to post your data and retrieve the sex selected by the user.

If you are using Razor view engine you should do something like this:

@{ 
    foreach (var sex in Model.SexList)
    {
        <div>
            @Html.RadioButtonFor(model => model.Sex, new { id = "sex" + sex.ID })
            @Html.Label("sex" + sex.ID, sex.Type)
        </div>
    }
}

Edit:

Your model should be something like this:

public class Student
{
    [Required(ErrorMessage = "First Name Required")] // textboxes will show
    [Display(Name = "First Name :")]
    [StringLength(5, ErrorMessage = "First Name cannot be longer than 5 characters.")]
    public string FirstName { get; set; }

    [Required(ErrorMessage = "Last Name Required")] // textboxes will show
    [Display(Name = "Last Name :")]
    [StringLength(5, ErrorMessage = "Last Name cannot be longer than 5 characters.")]
    public string LastName { get; set; }

    [Required(ErrorMessage = "Sex Required")]
    [Display(Name = "Sex :")]
    public Sex Gender { get; set; }

    public List<Sex> SexList { get; set; }

}

public class Sex
{
    public string ID {get;set;}
    public string Type {get;set;}
}

Your action in the controller:

[HttpGet]
public ActionResult Index()
{
    var student = new Student 
    {
        FirstName = "Rion",
        LastName = "Gomes",

        //I think the best way to populate this list is to call a service here.
        SexList = new List<Sex>
        {
            new Sex{ID="1" , Type = "Male"}, 
            new Sex{ID="2" , Type = "Female"}
        }    
    }    

    return View(student);
}

And the View:

@Html.BeginForm()
{
    <div>
        @Html.LabelFor(model => model.FirstName)
        @Html.EditorFor(model => model.FirstName)
        @Html.ValidationMessageFor(model => model.FirstName)
    </div>
    <div>
        @Html.LabelFor(model => model.LastName)
        @Html.EditorFor(model => model.LastName)
        @Html.ValidationMessageFor(model => model.LastName)
    </div>
    @{ 
        foreach (var sex in Model.SexList)
        {
            <div>
                @Html.RadioButtonFor(model => model.Gender, new { id = "sex" + sex.ID })
                @Html.Label("sex" + sex.ID, sex.Type)
            </div>
        }
    }

    <input type="submit" value"Submit" />
}

and you should have an action in your controller this way. This is the place where the submit is going to post the data:

[HttpPost]
public ActionResult Index(Student model)
{
    if (ModelState.IsValid)
    {
        //TODO: Save your model and redirect 
    }

    //Call the same service to initialize your model again (cause we didn't post the list of sexes)
    return View(model);
}

Leave a Comment