Checkbox value not posting in ASP.NET MVC form?


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.


Asked by:- pika
0
: 9295 At:- 9/14/2018 7:17:04 PM
ASP.NET MVC Razor checkbox value not posting mvc







2 Answers
profileImage Answered by:- Sam

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" />
  • If the checkbox is not checked, the form value for "IsLast" will be "false", as If checkbox remains unchecked, the form submits only the hidden value (false)
  • if it is checked, both values will be posted as "true,false". The model binder understands this, and will automatically take the true value from the collection of values.

OR

you can also try to use

@Html.CheckBoxFor(x => x.IsLast)

Thanks.

3
At:- 9/15/2018 5:34:58 PM Updated at:- 9/27/2022 7:39:08 AM


profileImage Answered by:- vikas_jk

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.

1
At:- 10/19/2018 9:11:13 AM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use