asp.net-mvc MVC4:单个布尔模型属性的两个单选按钮
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10518352/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MVC4: Two radio buttons for a single boolean model property
提问by AJ.
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:
我正在尝试为互斥的单选按钮找到正确的 Razor 语法,这些单选按钮都反映了我的模型上布尔属性的值。我的模型有这个:
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 IsFemaleproperty on the model. Currently, I have this:
我想用两个单选按钮来显示它,一个是“男性”,另一个是“女性”,但到目前为止我所尝试的一切都没有反映IsFemale模型上属性的实际价值。目前,我有这个:
@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.
如果我更改和更新,这似乎可以正确保留值,但不会将正确的值标记为已选中。我确定这是愚蠢的事情,但我被卡住了。
回答by Darin Dimitrov
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>
}
回答by Darren
In MVC 6 (ASP.NET Core) this can also be achieved with tag helpers:
在 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>

