locked
Pass Value[S] of multiple checkbox to Controller MVC | AJAX RRS feed

  • Question

  • User490317677 posted

    Hi :)

    Im loading contants dynamically to table as you see i have an input and i have two Checkbox:

            $.ajax({
                type: "GET",
                url: "/User/GetCustomerContactInfo",
                data: { ids: items },
                traditional: true,
                dataType: 'json',
                success: function (values) {
    
                  for (var i = 0; i < values.length; i++) {
                           value = values[i]
      
                          if (value != null) {
    
                           holderHTML += '<tr id="row' + value.CustomerNo + '">';
                           holderHTML += '<td><input id="NameOfCompany"  name="[' + i + '].NameOfCompany" value="' + value.NameOfCompany + '" /></td>';
                           holderHTML += '<td><input id="checkboxCustom1" type="checkbox" name="[' + i + '].RightsCode"  value="Åbne ordrer"/>
                                              <input id="checkboxCustom1" type="checkbox" name="[' + i + '].RightsCode"  value="Lukkede ordrer"/></td>
                           holderHTML += '</tr>';
                            }
                        }
    
                        $('#output').append(holderHTML);
    
                },
    
                error: function () {
                    console.log('something went wrong - debug it!');
                }
            })

    And HTML Output will be like:

    <form id="CustomerNEmployeeForm">
     <table>
    <tbody id="output">
    <tr id="row10883">
    <td>
    <input type="text" id="NameOfCompany" name="[0].NameOfCompany" value="Center">
    </td>
    <td>
    <input id="checkboxCustom1" type="checkbox" name="[0].RightsCode" value="Åbne ordrer">
    <input id="checkboxCustom1" type="checkbox" name="[0].RightsCode" value="Fakturerede ordrer">
    </td>
    </tr>
    </tbody>
    </table> </form>

    <button class="btncreateusers" id="createusersJS" type="button" onclick="CreateCustomerNEmployees();">Create</button>


     And than i want to get value of checkbox and pass to controller by Serialize form, but when form being Serialized, it will pass only value of first Checkbox:

     function CreateCustomerNEmployees() {
    
            var formdata = $("#CustomerNEmployeeForm").serializeArray();
    
            console.log(formdata);
    
            $.ajax({
                "url": '@Url.Action("CreateCustomers", "User")',
                "method": "POST",
                "data": formdata ,
                "dataType": "json",
    
                complete: function () {
                   
                }
    
            });
        }

    Output  console.log(formdata):

    0: {name: "[0].NameOfCompany", value: "Center"}
    1: {name: "[0].RightsCode", value: "Åbne ordrer"}
    2: {name: "[0].RightsCode", value: "Lukkede ordrer"}
    

    Model:

        public class CreateCustomers
        {
            public string NameOfCompany { get; set; }
            public string RightsCode { get; set; }
        }

    Controller:

     [HttpPost]
            public JsonResult CreateCustomers(List<CreateCustomers> model)
            {
    
           if (model == null)
                {
                    model = new List<CreateCustomers>();
                }
    
             var resultsOne = new List<Users>();
             var resultsTwo = new List<Rettigheder>();
    
    
          foreach (var item in model)
                {
    
               var UsersInsert = new Users
                    {
                        CompanyName = item.NameOfCompany,
                        //other property
                    };
    var RettighederInsert = new Rettigheder {
    //other property Rettighedskode = item.RightsCode }; resultsOne.Add(UsersInsert); db.Users.Add(UsersInsert); resultsTwo.Add(RettighederInsert); db.Rettigheder.Add(RettighederInsert); } db.SaveChanges(); return Json(model, JsonRequestBehavior.AllowGet); }

    Debug Output:

    Tuesday, August 13, 2019 2:12 PM

Answers

  • User665608656 posted

    Hi ManDown,

    According to your description and codes, If you only want to get the checkbox value, you don't need to use 'CustomerNEmployeeForm' to serializeArray, you could better to get the value of each checkbox by using jquery selector to get all checkboxes .

    Because your controller accepts List<Object> type, you can't use the serializeArray method. Instead, you should use the JSON.stringify method to ensure that the data types you pass to the controller are identical.

    You can refer to this link: Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax

    For more details, you could refer to the following code:

    <script type="text/javascript">
    
    
            function CreateCustomerNEmployees() {
            var formdata = [];
        $('input:checkbox').each(function() {
            var item = {};
    //here the item name should be the same as your model item ["NameOfCompany"]= $(this).attr("name"); item ["RightsCode"]= $(this).val(); formdata.push(item); });
    //here the model should be the same as your controller parameter name formdata = JSON.stringify({ 'model': formdata }); console.log(formdata); $.ajax({ contentType: 'application/json; charset=utf-8',//this statement should be added "url": '@Url.Action("CreateCustomers", "User")', "method": "POST", "data": formdata, "dataType": "json", complete: function () { } }); }

    This is the result of debugging in controller :

    Best Regards,

    YongQing.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, August 14, 2019 3:12 AM

All replies

  • User-821857111 posted

    Change your RightsCode property to an array if you want more than one value to be bound:

    public string[] RightsCode { get; set; }
    Tuesday, August 13, 2019 2:25 PM
  • User665608656 posted

    Hi ManDown,

    According to your description and codes, If you only want to get the checkbox value, you don't need to use 'CustomerNEmployeeForm' to serializeArray, you could better to get the value of each checkbox by using jquery selector to get all checkboxes .

    Because your controller accepts List<Object> type, you can't use the serializeArray method. Instead, you should use the JSON.stringify method to ensure that the data types you pass to the controller are identical.

    You can refer to this link: Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax

    For more details, you could refer to the following code:

    <script type="text/javascript">
    
    
            function CreateCustomerNEmployees() {
            var formdata = [];
        $('input:checkbox').each(function() {
            var item = {};
    //here the item name should be the same as your model item ["NameOfCompany"]= $(this).attr("name"); item ["RightsCode"]= $(this).val(); formdata.push(item); });
    //here the model should be the same as your controller parameter name formdata = JSON.stringify({ 'model': formdata }); console.log(formdata); $.ajax({ contentType: 'application/json; charset=utf-8',//this statement should be added "url": '@Url.Action("CreateCustomers", "User")', "method": "POST", "data": formdata, "dataType": "json", complete: function () { } }); }

    This is the result of debugging in controller :

    Best Regards,

    YongQing.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, August 14, 2019 3:12 AM