MVC4: two switches for one property of a boolean model

I am trying to find the right Razor syntax for mutually exclusive switches that reflect the value of a boolean property in my model. My model has the following:

public bool IsFemale{ get; set; } 

I would like to show this with two switches: “Male” and the other “Female”, but everything I have tried so far has not reflected the actual value of the IsFemale property on the model. I currently have this:

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

It is like storing a value correctly if I change and update, but don’t check the correct value as noted. I'm sure this is something stupid, but I'm stuck.

+46
asp.net-mvc razor asp.net-mvc-4
May 09 '12 at 14:40
source share
2 answers

Try it like this:

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

And here is 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> } 
+85
May 9 '12 at 2:47 p.m.
source share

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

 <label> <input type="radio" asp-for="IsFemale" value="false" /> Male </label> <label> <input type="radio" asp-for="IsFemale" value="true" /> Female </label> 
0
Dec 05 '17 at 15:35
source share



All Articles