Search code examples
asp.net-corerazorasp.net-core-mvccheckboxfor

ASP.NET Core 2 MVC CheckBoxFor always returning false in model


I know there were a number of people that faced this issue but I don't feel like they ever resolved it.

I have a razor page like this:

@model MyModel
<div>
    @using (Html.BeginForm("MyMethod", "Home", FormMethod.Get))
    {
        @Html.CheckBoxFor(model => model.MyBool)
        @Html.LabelFor(model => model.MyBool)
        <input type="submit" class="btn" value="Fire it up" />
    }
</div>

My model looks like this:

public class MyModel
{
    [DisplayName("My checkbox")]
    public bool MyBool {get; set;}
}

And my method in the home controller looks like this:

public IActionResult MyMethod(MyModel model)
{
    return View();
}

Everything looks good to me, but then, no matter if I check the checkbox or not, the model parameter in the MyMethod method is always false after I submit the form.

What am I doing wrong?

EDIT:

When I check the checkbox the GET request contains both values - true and false. I saw some people say that MVC should handle it but it apparently doesn't.


Solution

  • So, what happens is that when you don't check an HTML checkbox, the value sent by default is null. But when you are using the HTML helper @Html.CheckBoxFor(model => model.MyBool), it is automatically creating a Checkbox for the MyBool value as you asked, and additionally a @Html.Hidden("MyBool",false). What this will do is, if MyBool doesn't have any value (if checkbox isn't checked), it will pass False, instead of null.

    HTML created:

      <input id="MyBool" name="MyBool" type="checkbox" value="true">
      <input name="MyBool" type="hidden" value="false">