0

When clicking on the checkbox, form is submitted using jQuery, but checkbox always return null.

I have the following Razor code:

@using (Html.BeginForm("Index", "HumanResource", new { type = ViewBag.CurrentType }, FormMethod.Post, new { id = "form1" }))
{
 <label class="custom-control custom-checkbox" for="Filter">
        @Html.CheckBox("Filter", new { @class = "custom-control-input" })
        <span class="custom-control-indicator"></span>
        Choose
 </label>
}

// Scripts

<script>
$('#form1 :checkbox').change(function() {
            $("#form1").submit();
   });
</script>

Controller

public async Task<ActionResult> Index(FormCollection fc,int? Filter)
{
    // leftFilter is always null
}
3
  • 3
    Checkbox submits boolean, not an int Commented Aug 13, 2018 at 14:25
  • @Andrei I didn't have problem regarding if it's boolean or not, after I changed theme's files, that's happened. Commented Aug 13, 2018 at 14:28
  • 1
    That is exactly your problem, when model binder cannot parse the value it sets variable to null instead. 'true' and 'false' cannot be parse to int Commented Aug 13, 2018 at 15:19

1 Answer 1

3

When the form is submitted, the browser will send either true or false for filter input in form data, to the form action URL( the action method which handles the form submit). You are using a nullable int(int?) as the parameter to accept the value of filter. The model binder cannot map a boolean value to a nullable int. How does it know what value to assign in the numeric parameter for true /false ? It can map the incoming boolean value to only a boolean parameter.

So change your parameter type to bool.

[HttpPost]
public async Task<ActionResult> Index4(FormCollection fc, bool filter)
{
    //to so : return something
}

Now when the form is submitted, the filter parameter will be populated with a value.

Suggestion: Submitting a form when user clicks on the checkbox seems like a bad user experience IMHO, what if user wants to change ? How about adding a separate "search" button and submit the form when user clicks on that after making the checkbox selections ? Or perhaps consider some client side/ajax sort of filtering.

Sign up to request clarification or add additional context in comments.

1 Comment

I agree with @Shyju about the checkbox being used for submitting the form. It's bad UX.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.