I am trying to get a value( 1 or 0) from a checkbox using FormCollection
. But even I check it I get 0 in debugger mode.
Here, is the checkbox.
<label class="form-check-label">
<input id="UbankInsurance" name="UbankInsurance" value="1" type="checkbox"/> Yes
</label>
and here is the method to collect it.
[HttpPost]
public ActionResult Edit(FormCollection fc)
{
int ublInsurance = Convert.ToInt32(fc["UbankInsurance"]);
}
and further im going to pass this value to a database column that has a bit
Data type
Your code looks fairly correct, so I suppose you have not passed your checkbox in a form
to begin with. Furthermore you need to check that value for null
. If a checkbox is checked, the value "1"
is submitted as a string. If it is unchecked, the value null will be returned.
Here is a working example:
<h3>Submitted value: @TempData["val"]</h3>
@using (Html.BeginForm("GetCheckbox", "Home", FormMethod.Post))
{
<label class="form-check-label">
<input id="UbankInsurance" name="UbankInsurance" value="1" type="checkbox" />
Yes
</label>
<button type="submit">Submit</button>
}
Controller Method:
[HttpPost]
public ActionResult GetCheckbox(FormCollection form)
{
var checkboxChecked = form["UbankInsurance"]; //get the checkbox value
if(checkboxChecked == null) //if it is unchecked it will be null
{
checkboxChecked = "0"; //set it to a parsable value instead
}
//convert 0 or 1 to int and return it to view
TempData["val"] = Convert.ToInt32(checkboxChecked);
return View("Index");
}
Please not, that I have used the HomeController in a demo application, so make sure you fill in your actual values in terms of action methods and controller names.
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.