如何在ASP.NET MVC中验证复选框值?

时间:2016-07-25 21:30:28

标签: c# asp.net asp.net-mvc validation asp.net-mvc-5

我有以下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时,我传递了值0IsCorrect,但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

1 个答案:

答案 0 :(得分:2)

确保您正确传递参数

您是否尝试明确传递truefalse(即Controller/Action?IsCorrect=true)而不是0或1?

复选框应始终直接绑定到布尔值。您只需要确保复选框的name属性与您的参数或模型属性完全匹配(即IsCorrect):

<!-- Using a plain CheckBox -->
<input name='IsCorrect' type='checkbox' />
<!-- Using an HTML Helper -->
@Html.CheckBox("IsCorrect")

您可以see a working example demonstrating this以下:

enter image description here