Why do my checkboxes not pass their value to my controller in ASP.NET Core?

后端 未结 3 1063
闹比i
闹比i 2021-01-14 13:49

I feel this may be an easy fix but I cannot seem to get around it. I have an ASP.NET Core web application and I\'m using an ajax form to submit data to my controller for pr

相关标签:
3条回答
  • 2021-01-14 14:26

    As you are using ASP.NET Core, it is recommend to use the Tag Helpers:

    <div class="form-group">
        <label asp-for="@Model.ColName"></label>
        <input asp-for="@Model.ColName" type="checkbox" />
    </div>
    
    0 讨论(0)
  • 2021-01-14 14:34

    If not using asp-for attribute , you can modify your codes to add a hidden field. It will be submitted regardless whether the checkbox is checked or not. If the checkbox is checked, the posted value will be true,false. The model binder will correctly extract true from the value. Otherwise it will be false :

    <input type="checkbox" class="custom-control-input" data-val="true" id="ColName" name="ColName" value="true" checked>
    <label class="custom-control-label" for="ColName">Name</label>
    <input name="ColName" type="hidden" value="false">
    
    0 讨论(0)
  • 2021-01-14 14:40

    I ran into a similar issue. There is a form we have that contains many fields that include textboxes, select (dropdown) menus, checkboxes and of course labels. All fields save to the database properly EXCEPT for the three checkbox options we have. I just figured out the fix after fooling with it off and on for weeks. I hope this helps someone:

    This is what the code used to look like:

    $(this).attr('data-val', 'true');
    

    This is what fixed the problem:

    $(this).val(true);
    

    Here is the whole function that includes the fix:

    $('form').on('change', ':checkbox', function () {
        if (this.checked) {
            $(this).val(true);
        }
        else {
            $(this).val(false);
        }
    });
    
    
    0 讨论(0)
提交回复
热议问题