I am trying to submit the form in ASP.NET MVC by updating a value of checkbox, but checkbox is not posting updated value to the C# Controller and posting null value, here is my razor code
<div class="row">
<div class="col-lg-12">@Html.Label("Is Last")</div>
<div class="col-lg-12"><input type="checkbox" name="IsLast" id="IsLast" value="@Model.IsLast" /></div>
</div>
and here is my C# Controller code
public ActionResult EditTutorial(StudentsModal stu)
{
using (var context = new Modalentites())
{
//c# code here get modal data and save new changes
// stu.IsLast = null here
}
return View();
}
How to make it work? Thanks.
Try using
@Html.EditorFor(x => x.IsLast)
It will generate output as below
<input id="IsLast" type="checkbox" value="true" name="IsLast" />
<input type="hidden" value="false" name="IsLast" />
OR
you can also try to use
@Html.CheckBoxFor(x => x.IsLast)
Thanks.
To do a checkbox in Mvc use
@Html.CheckBoxFor(x => x.IsLast)
OR if you don't want to bind the model to the view.
@Html.CheckBox("IsLast")
Mvc automatically adds a hidden field to persist values when they are not selected.
OR You can use jQuery Solution(not recommended):
$("input[type=checkbox]").change(function () {
if ($(this).prop("checked")) {
$(this).val(true);
} else {
$(this).val(false);
}
});
Any of the above solution works.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly