我有一个模型如下
public partial class Approval
{
public bool IsApproved { get; set; }
}
在视图中渲染模型时,我正在使用用于IsApproved属性的无线电按钮
@Html.RadioButtonFor(model => model.IsApproved, "Yes", htmlAttributes: new { @id = "Approve"})
@Html.Label("Yes", htmlAttributes: new { @style = "padding-right:10px;vertical-align:top" })
@Html.RadioButtonFor(model => model.IsApproved, "No", htmlAttributes: new { @id = "Reject", })
@Html.Label("No", htmlAttributes: new { @style = "padding-right:10px;vertical-align:top" })
提交时,我得到ModelState.IsValid为false,因为IsApproved的类型为bool,我在View中传递字符串
如果我更改单选按钮
@Html.RadioButtonFor(model => model.IsApproved, Model.IsApproved, htmlAttributes: new { @id = "Approve"})
@Html.RadioButtonFor(model => model.IsApproved, !Model.IsApproved, htmlAttributes: new { @id = "Reject", })
默认情况下,单选按钮会在我不想要的页面加载中进行检查。
建议正确的方法
答案 0 :(得分:0)
控制器:
public ActionResult Index()
{
return View(Approval)
{
IsApproved = true;
});
}
[HttpPost]
public ActionResult Index(Approval Approvalmodel)
{
return Content("IsApproved: " + Approvalmodel.IsApproved);
}
查看:
@model Approval
@using (Html.BeginForm())
{
@Html.RadioButtonFor(model => model.IsApproved, "true", new { id = "Approved" })
@Html.Label("Yes", htmlAttributes: new { @style = "padding-right:10px;vertical-align:top" })
@Html.RadioButtonFor(model => model.IsApproved, "false", new { id = "Rejected" })
@Html.Label("No", htmlAttributes: new { @style = "padding-right:10px;vertical-align:top" })
<button type="submit">OK</button>
}