Bercovici Adrian
Bercovici Adrian

Reputation: 9370

Checkbox input remains false on form submit

I am trying to post a form and even though all the inputs map their value accordingly in the receiving controller-method , the bool-s of checkbox-es remain false. What am i doing wrong ?

POCO

class MyPoco
{ 
   public string User{get;set;}
   public bool Require {get;set;}
}

Form

<form id="createForm" method="post" action="[some url]">

<input type="checkbox" id="require" name="Require" />

<input type="text" id="user" name="User"/>

</form>

Controller (method)

 [HttpPost]
 [Route("[some url]")]
 public async Task<long> CreateAsync(MyPoco request)
 {

 }

Why in my case above does request.Require is always false.I have mapped them correctly (the name attribute).

Upvotes: 1

Views: 1031

Answers (2)

TanvirArjel
TanvirArjel

Reputation: 32099

I see you are missing asp-for attribute for your checkbox input. Instead of name="Require", use asp-for="Require" as follows:

@model MyPoco

<input asp-for="Require" type="checkbox" id="require"  />

If you don't want to use asp-for attribute then you have to use jQuery as follows:

$(document).on('change','#require',function() { 
    if ($(this).is(':checked')) {
        $(this).val(true) 
    } else {
        $(this).val(false) 
     }
});

Upvotes: 2

Ryan
Ryan

Reputation: 20116

The reason is that you forget to set value of checkbox:

<input type="checkbox" id="require" name="Require" value="true" />

If a checkbox is checked, then the postback values will contain a key-value pair of the form [InputName]=[InputValue]

If a checkbox is not checked, then the posted form contains no reference to the checkbox at all.

Upvotes: 2

Related Questions