MVC4:对于一个布尔模型属性的两个单选按钮(MVC4: Two radio buttons for

2019-06-24 07:11发布

我试图找到相互排斥的单选按钮既反映了布尔属性在我的模型中的价值正确的剃刀语法。 我的模型具有这样的:

public bool IsFemale{ get; set; }

我想有两个单选按钮,一个“男”,另一个显示这个“女”,但一切我试过到目前为止还没有反映的实际值IsFemale的模型属性。 目前,我有这样的:

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

这似乎是坚持正确的价值,如果我改变和更新,但由于检查没有标注正确的值。 我敢肯定,这是愚蠢的东西,但我坚持。

Answer 1:

尝试这样的:

@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>
}


Answer 2:

在MVC 6(ASP.NET核心)这也与标签帮手来实现:

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


文章来源: MVC4: Two radio buttons for a single boolean model property