我有以下ViewModel
public class ReportFilters
{
[Required]
public DateTime From { get; set; }
[Required]
public DateTime To { get; set; }
[Required]
public int UserId { get; set; }
public bool IsCorrect { get; set; }
}
当我将此路由调用1
时,我传递了值0
或IsCorrect
,但ModelState.IsValid
始终返回false。
在我添加public bool IsCorrect { get; set; }
以下是我的控制器操作的样子
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult GetTotals([Bind(Include = "From,To,UserId,IsCorrect ")] ReportFilters reportFilters)
{
if (ModelState.IsValid)
{
SomeModel results;
if(reportFilters.IsCorrect)
{
results = conn.Database.SqlQuery<SomeModel>(SomeQuery, from, to).ToList();
} else
{
results = conn.Database.SqlQuery<SomeModel>(SomeOtherQuery, from, to).ToList();
}
return Json(results, JsonRequestBehavior.AllowGet);
}
return Json(new { }, JsonRequestBehavior.AllowGet);
}
问题
如何正确验证复选框的值?如果值为1
,那么它应为true
,否则为false
。
答案 0 :(得分:2)
确保您正确传递参数
您是否尝试明确传递true
或false
(即Controller/Action?IsCorrect=true
)而不是0或1?
复选框应始终直接绑定到布尔值。您只需要确保复选框的name
属性与您的参数或模型属性完全匹配(即IsCorrect
):
<!-- Using a plain CheckBox -->
<input name='IsCorrect' type='checkbox' />
<!-- Using an HTML Helper -->
@Html.CheckBox("IsCorrect")