1

How do I check if a checkbox value is true when the result is either {false} for not checked and {true,false} for checked? When I add value="yes" to the helper i get {yes,false} for checked. {Sidebar: What is so wrong with Microsoft they can't get this right?}

{Versions: netcoreapp3.1, Microsoft.EntityFrameworkCore 3.1.5, Microsoft.VisualStudio.Web.CodeGeneration.Design 3.1.3, VS Enterprise 2019 16.6.3}

View:

<div class="form-group form-check">
<label class="form-check-label">
    <input class="form-check-input" asp-for="MyBoolValue" /> @Html.DisplayNameFor(model => model.MyBoolValue)
</label>
</div>

Controller: (with IFormCollection form)

if(form["MyBoolValue"].ToString() != "") // Does not work when the value is {false} not checked
{
    DbTable.MyBoolValue = true;
}
else
{
    DbTable.MyBoolValue = false;
}

I've tried many combinations like:

if(Convert.ToBoolean(form["MyBoolValue"]) == true)

Anyone have a simple way to get a true false condition consistently from a checkbox?

Mattman85208
  • 1,858
  • 2
  • 29
  • 51
  • This will probably help you: https://stackoverflow.com/questions/57079165/why-do-my-checkboxes-not-pass-their-value-to-my-controller-in-asp-net-core – CCBet Jul 08 '20 at 20:56
  • This works: DbTable.MyBoolValue = Convert.ToBoolean(form["MyBoolValue "][0]); or this would work: if (form["MyBoolValue "][0].Equals("true")) {might need ToString} or if(Convert.ToBoolean(form["MyBoolValue"][0]) == true) – Mattman85208 Jul 09 '20 at 16:13

1 Answers1

1

enter image description here

The second field is a hidden field. It will be submitted regardless whether the checkbox is checked or not. If the checkbox is checked, the posted value will be true,false. Else,the posted value will be false.It is caused by design. If you want to check the checkbox is true or false,You can do like this:

Controller:

 public IActionResult Test(IFormCollection form) {
            string[] str = form["MyBoolValue"].ToArray();
            //the first solution
            if (str.Length > 1)
            {
                //MyBoolValue is true
            }
            else {
                //MyBoolValue is false
            }
            //the second solution
            if (str[0].Equals("true"))
            {
                //MyBoolValue is true
            }
            else
            {
                //MyBoolValue is false
            }
            return View();
        }
    }
Yiyi You
  • 16,875
  • 1
  • 10
  • 22
  • Yiyi You - I think your answer is correct. But, this works for me and seem simpler: DbTable.MyBoolValue = Convert.ToBoolean(form["MyBoolValue "][0]); or this would work: if (form["MyBoolValue "][0].Equals("true")) or if(Convert.ToBoolean(form["MyBoolValue"][0]) == true) I do not need to convert it to an Array and it works fine. Many Thanks!!! – Mattman85208 Jul 09 '20 at 16:10