MVC4: Two radio buttons for a single boolean model property

asp.net MvcRazorasp.net Mvc-4Radiobuttonfor

asp.net Mvc Problem Overview


I'm attempting to find the correct Razor syntax for mutually exclusive radio buttons that both reflect the value of a boolean property on my model. My model has this:

public bool IsFemale{ get; set; }

I would like to display this with two radio buttons, one "Male" and the other "Female," but everything I've tried so far has not reflected the actual value of the IsFemale property on the model. Currently, I have this:

@Html.RadioButtonFor(model => model.IsFemale, !Model.IsFemale) Male
@Html.RadioButtonFor(model => model.IsFemale, Model.IsFemale) Female

This seems to persist the value correctly if I change and update, but does not mark the correct value as checked. I'm sure this is something stupid, but I'm stuck.

asp.net Mvc Solutions


Solution 1 - asp.net Mvc

Try like this:

@Html.RadioButtonFor(model => model.IsFemale, "false") Male
@Html.RadioButtonFor(model => model.IsFemale, "true") Female

And here's the full code:

Model:

public class MyViewModel
{
    public bool IsFemale { get; set; }
}

Controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new MyViewModel
        {
            IsFemale = true
        });
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        return Content("IsFemale: " + model.IsFemale);
    }
}

View:

@model MyViewModel

@using (Html.BeginForm())
{
    @Html.RadioButtonFor(model => model.IsFemale, "false", new { id = "male" }) 
    @Html.Label("male", "Male")

    @Html.RadioButtonFor(model => model.IsFemale, "true", new { id = "female" })
    @Html.Label("female", "Female")
    <button type="submit">OK</button>
}

Solution 2 - asp.net Mvc

In MVC 6 (ASP.NET Core) this can also be achieved with tag helpers:

<label>
    <input type="radio" asp-for="IsFemale" value="false" /> Male
</label>
<label>
    <input type="radio" asp-for="IsFemale" value="true" /> Female
</label>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAJ.View Question on Stackoverflow
Solution 1 - asp.net MvcDarin DimitrovView Answer on Stackoverflow
Solution 2 - asp.net MvcDarrenView Answer on Stackoverflow