MVC4: Two radio buttons for a single boolean model property

前端 未结 2 974
清歌不尽
清歌不尽 2020-12-13 03:33

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:

2条回答
  •  北海茫月
    2020-12-13 04:21

    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")
        
    }
    

提交回复
热议问题