简体   繁体   中英

How do I validate a checkbox value in ASP.NET MVC?

I have the following 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; }
} 

I pass either the value 1 or 0 when I call this route to IsCorrect but the ModelState.IsValid is always returning false.

This started to happen after I added public bool IsCorrect { get; set; } public bool IsCorrect { get; set; }

Here is how my controller action look like

[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);

}

Question

How can I correctly validate the value of a check box? If the value is 1 then it should be true otherwise false .

Ensure You Are Passing Your Parameters Properly

Have you tried passing true or false explicitly (ie Controller/Action?IsCorrect=true ) as opposed to a 0 or 1?

A checkbox should always bind directly to a boolean value. You'll just need to ensure that the name attribute of your checkbox matches your parameter or model property exactly (ie IsCorrect ) :

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

You can see a working example demonstrating this below :

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM