62

我正在尝试为互斥的单选按钮找到正确的 Razor 语法,这些单选按钮都反映了我的模型上的布尔属性的值。我的模型有这个:

public bool IsFemale{ get; set; }

我想用两个单选按钮来显示这个,一个是“男性”,另一个是“女性”,但到目前为止我尝试的所有内容都没有反映IsFemale模型上属性的实际值。目前,我有这个:

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

如果我更改和更新,这似乎可以正确地保留该值,但不会将正确的值标记为已选中。我敢肯定这是愚蠢的,但我被困住了。

4

2 回答 2

115

试试这样:

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

这是完整的代码:

模型:

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

控制器:

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

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

看法:

@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>
}
于 2012-05-09T14:47:42.273 回答
12

在 MVC 6 (ASP.NET Core) 中,这也可以通过标签助手来实现:

<label>
    <input type="radio" asp-for="IsFemale" value="false" /> Male
</label>
<label>
    <input type="radio" asp-for="IsFemale" value="true" /> Female
</label>
于 2017-12-05T15:35:04.777 回答