我正在尝试为互斥的单选按钮找到正确的Razor语法,这两个按钮都反映了模型上布尔属性的值。我的模型有这个:
public bool IsFemale{ get; set; }
我想用两个单选按钮显示它,一个是“男性”,另一个是“女性”,但到目前为止我尝试的所有内容都没有反映模型上IsFemale
属性的实际值。目前,我有这个:
@Html.RadioButtonFor(model => model.IsFemale, !Model.IsFemale) Male
@Html.RadioButtonFor(model => model.IsFemale, Model.IsFemale) Female
如果我更改并更新,这似乎会正确保留该值,但不会将正确的值标记为已选中。我确定这是愚蠢的,但我被卡住了。
答案 0 :(得分:97)
试试这样:
@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>
}
答案 1 :(得分:3)
在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>