locked
Model return NULL trying Pass values of Selected checkboxes RRS feed

  • Question

  • User490317677 posted

    I have a view with a number of checkboxes in it. I want to be able to pass the values of the checkboxes to the controller by Serialize form, but my Model return NULL and it cant quit catch checkbox value from view to controller. Can anyone please help me or point me into right direction ! :)

    Here is the View:

    @model CreateCustomers
    
    <form id="CustomerNEmployeeForm">
    
       @{ 
            var newGuid = Guid.NewGuid();
        }
    
     <input type="hidden" name="RightsCodes.Index" value='@newGuid' />
     <div><input type="checkbox" name="[@newGuid].RightsCodes.OpenOrders" value="true" class="checkbox-template"><label for="checkboxCustom1"bne ordrer</label></div>
     <div><input type="checkbox" name="[@newGuid].RightsCodes.ClosedOrders" value="true" class="checkbox-template"><label for="checkboxCustom1">Lukkede ordrer</label></div>
     <div><input type="checkbox" name="[@newGuid].RightsCodes.Deliveries" value="true" class="checkbox-template"><label for="checkboxCustom1">Leverancer</label></div>
     <div><input type="checkbox" name="[@newGuid].RightsCodes.RMA" value="true" class="checkbox-template"><label for="checkboxCustom1">RMA</label></div>
     <div><input type="checkbox" name="[@newGuid].RightsCodes.SellingPrices" value="true" class="checkbox-template"><label for="checkboxCustom1">Se salgspriser</label></div>
     <div><input type="checkbox" name="[@newGuid].RightsCodes.FullAccess" value="true" class="checkbox-template"><label for="checkboxCustom1">Fuld adgang</label></div>
     <div><input type="checkbox" name="[@newGuid].RightsCodes.UserAdmin" value="true" class="checkbox-template"><label for="checkboxCustom1">User admin</label></div>
    
    </form>

    JavaScript:

    <script>
        function CreateCustomerNEmployees() {
    
          var formdata = $("#CustomerNEmployeeForm").serializeArray();
    
           $.ajax({
                    "url": '@Url.Action("CreateCustomers", "User")',
                    "method": "POST",
                    "data": formdata ,
                    "dataType": "json",
                    complete: function () {
                        console.log('Ok');
                    },
                    error: function () {
                        console.log('something went wrong - debug it!');
                    }
    
                });
        }
    
    </script>

    ViewModel:

    public class CreateCustomers
        {
      public RightCodes RightsCodes { get; set; }
      public class RightCodes
            {
                public bool OpenOrders { get; set; }
                public bool ClosedOrders { get; set; }
                public bool RMA { get; set; }
                public bool Deliveries { get; set; }
                public bool SellingPrices { get; set; }
                public bool UserAdmin { get; set; }
                public bool FullAccess { get; set; }
    
                public List<string> Trues()
                {
                    var results = new List<string>();
                    if (OpenOrders)
                        results.Add("Åbne ordrer");
                    if (ClosedOrders)
                        results.Add("Lukkede ordrer");
                    if (RMA)
                        results.Add("RMA");
                    if (Deliveries)
                        results.Add("Leverancer");
                    if (SellingPrices)
                        results.Add("Se salgspriser");
                    if (UserAdmin)
                        results.Add("User Admin");
                    if (FullAccess)
                        results.Add("Fuld adgang");
                    return results;
                }
            }
    
       }

    Controller:

      [HttpPost]
            public JsonResult CreateCustomers(List<CreateCustomers> model)
            {
                 var resultsThree = new List<Rights>();
                 foreach (var item in model)
                  {
    
                    foreach (var right in item.RightsCodes.Trues())
                    {
                        var RettighederInsert = new Rights
                        {
                            //PX2ID = px2id,
                            Rettighedskode = right,
                            IsChecked = true
    
                        };
    
                        db.Rights.Add(RettighederInsert);
                    }
                  }
    
                db.SaveChanges();
                return Json(model, JsonRequestBehavior.AllowGet);
           }

    Output after serialising (For ex if i checked first checkbox) :

    0: {name: "RightsCodes.Index", value: "45f57034-0e99-402c-bcf4-1d28ac1e50fd"}
    1: {name: "[45f57034-0e99-402c-bcf4-1d28ac1e50fd].RightsCodes.OpenOrders", value: "true"}

    Tuesday, September 17, 2019 1:46 PM

Answers

  • User-17257777 posted

    Hi ManDown,

    As mgebhard said, you only have one form on the page, so just use the single type. Also, if you want to recevie the data by using model, you should keep the name of input consistent with the fields in the model. I made some changes to your codes, and had a test:

    View:

    <form id="CustomerNEmployeeForm">
    
        @{
            var newGuid = Guid.NewGuid();
        }
    
        <input type="hidden" name="RightsCodes.Index" value='@newGuid' />
        <div><input type="checkbox" name= "model.RightsCodes.OpenOrders" value="true" class="checkbox-template"><label for="checkboxCustom1">Åbne ordrer</label></div>
        <div><input type="checkbox" name= "model.RightsCodes.ClosedOrders" value="true" class="checkbox-template"><label for="checkboxCustom1">Lukkede ordrer</label></div>
        <div><input type="checkbox" name= "model.RightsCodes.Deliveries" value="true" class="checkbox-template"><label for="checkboxCustom1">Leverancer</label></div>
        <div><input type="checkbox" name= "model.RightsCodes.RMA" value="true" class="checkbox-template"><label for="checkboxCustom1">RMA</label></div>
        <div><input type="checkbox" name= "model.RightsCodes.SellingPrices" value="true" class="checkbox-template"><label for="checkboxCustom1">Se salgspriser</label></div>
        <div><input type="checkbox" name= "model.RightsCodes.FullAccess" value="true" class="checkbox-template"><label for="checkboxCustom1">Fuld adgang</label></div>
        <div><input type="checkbox" name= "model.RightsCodes.UserAdmin" value="true" class="checkbox-template"><label for="checkboxCustom1">User admin</label></div>
    
    </form>
    
    <input type="button" onclick="CreateCustomerNEmployees()" value="submit" />

    javascript:

    <script>
        function CreateCustomerNEmployees() {
            
            var formdata = $("#CustomerNEmployeeForm").serializeArray();
            
            $.ajax({
                "url": '@Url.Action("CreateCustomers", "User")',
                "method": "POST",
                "data": formdata,
                "dataType": "json",
                complete: function () {
                    console.log('Ok');
                },
                error: function () {
                    console.log('something went wrong - debug it!');
                }
    
            });
        }
    
    </script>

    Controller:

    [HttpPost]
            public JsonResult CreateCustomers(CreateCustomers model)
            {
                foreach(var right in model.RightsCodes.Trues())
                {
                    //Your Codes
                }
                
                //db.SaveChanges();
                return Json(model, JsonRequestBehavior.AllowGet);
            }

    Test Result:

    Best Regards,

    Jiadong Meng

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, September 19, 2019 5:57 AM

All replies

  • User-474980206 posted
    Remove the [@newGuid]. prefix from the names. Not sure what you where trying to do.
    Tuesday, September 17, 2019 2:10 PM
  • User475983607 posted

    Output after serialising (For ex if i checked first checkbox) :
    0: {name: "RightsCodes.Index", value: "45f57034-0e99-402c-bcf4-1d28ac1e50fd"}
    1: {name: "[45f57034-0e99-402c-bcf4-1d28ac1e50fd].RightsCodes.OpenOrders", value: "true"}

    This is the expected result of serialization.  However, not the expected payload. 

    There are several issues with the design.  The HTML form does not contain a collection.  There is no need to format the inputs as a collection or use an index.  Use a single type rather than a collection.

    Unchecked checkboxes are not submitted in a forum post.  Since the bool type defaults to false the properties that do not have input values will default to false or unchecked.

    Tuesday, September 17, 2019 2:24 PM
  • User-17257777 posted

    Hi ManDown,

    As mgebhard said, you only have one form on the page, so just use the single type. Also, if you want to recevie the data by using model, you should keep the name of input consistent with the fields in the model. I made some changes to your codes, and had a test:

    View:

    <form id="CustomerNEmployeeForm">
    
        @{
            var newGuid = Guid.NewGuid();
        }
    
        <input type="hidden" name="RightsCodes.Index" value='@newGuid' />
        <div><input type="checkbox" name= "model.RightsCodes.OpenOrders" value="true" class="checkbox-template"><label for="checkboxCustom1">Åbne ordrer</label></div>
        <div><input type="checkbox" name= "model.RightsCodes.ClosedOrders" value="true" class="checkbox-template"><label for="checkboxCustom1">Lukkede ordrer</label></div>
        <div><input type="checkbox" name= "model.RightsCodes.Deliveries" value="true" class="checkbox-template"><label for="checkboxCustom1">Leverancer</label></div>
        <div><input type="checkbox" name= "model.RightsCodes.RMA" value="true" class="checkbox-template"><label for="checkboxCustom1">RMA</label></div>
        <div><input type="checkbox" name= "model.RightsCodes.SellingPrices" value="true" class="checkbox-template"><label for="checkboxCustom1">Se salgspriser</label></div>
        <div><input type="checkbox" name= "model.RightsCodes.FullAccess" value="true" class="checkbox-template"><label for="checkboxCustom1">Fuld adgang</label></div>
        <div><input type="checkbox" name= "model.RightsCodes.UserAdmin" value="true" class="checkbox-template"><label for="checkboxCustom1">User admin</label></div>
    
    </form>
    
    <input type="button" onclick="CreateCustomerNEmployees()" value="submit" />

    javascript:

    <script>
        function CreateCustomerNEmployees() {
            
            var formdata = $("#CustomerNEmployeeForm").serializeArray();
            
            $.ajax({
                "url": '@Url.Action("CreateCustomers", "User")',
                "method": "POST",
                "data": formdata,
                "dataType": "json",
                complete: function () {
                    console.log('Ok');
                },
                error: function () {
                    console.log('something went wrong - debug it!');
                }
    
            });
        }
    
    </script>

    Controller:

    [HttpPost]
            public JsonResult CreateCustomers(CreateCustomers model)
            {
                foreach(var right in model.RightsCodes.Trues())
                {
                    //Your Codes
                }
                
                //db.SaveChanges();
                return Json(model, JsonRequestBehavior.AllowGet);
            }

    Test Result:

    Best Regards,

    Jiadong Meng

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, September 19, 2019 5:57 AM