Mattman85208
Mattman85208

Reputation: 2100

ASP.NET CORE Checkbox how to check for true?

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?

Upvotes: 1

Views: 3386

Answers (1)

Yiyi You
Yiyi You

Reputation: 18199

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();
        }
    }

Upvotes: 1

Related Questions