skip to Main Content

html form:

<form name="CarServ" id="myForm">
            <div>
                <label>CarModel:</label>
                <input type="text" id="model" size="65" name="CarModel" placeholder="Enter Car Model" required>
            </div>
            <div>
                <label>Car Number:</label>
                <input type="text" size="65" id="num" name="CarNumber" placeholder="Enter Car Number" required >
            </div>
            <div>
                <label>Contact number:</label>
                <input type="text" size="65" id="cnum" name="ContactNumber" placeholder="Enter your contact number" required>
            </div>


            <div id="service" class="opt">
                <label>Type of service:</label>
                <input type="radio" name="TypeOfService" id="t1" value="Waterwash"required>
                <label for="t1">Waterwash</label>
                <input type="radio" name="TypeOfService" id="t2" value="Fullservice" required>
                <label for="t1">Fullservice</label>
    
    
            </div>
            <br/>

            <div class="check">
    
                <label>Addons:</label>
    
                <input type="checkbox" name ="SelectedCheckboxes[]" value="10%off First service visit" id="10%off First service visit">
                <label for="10%off First service visit">10%off First service visit</label>
                <input type="checkbox" name="SelectedCheckboxes[]" value="10%off Waterwash"  id="10%off Waterwash">
                <label for="10%off Waterwash">10%off Waterwash</label>


                <input type="checkbox" name ="SelectedCheckboxes[]" value="Free AC Inspection" id="Free AC Inspection">
                <label for="Free AC Inspection">Free AC Inspection</label>


            </div>  

    
            <div class="dropd">
                <label>Select State:</label>
                    <select class="form-control" name ="SelectState" id="select1">
                        <option value="0" selected="" disabled="">--SELECT--</option>
                        <option value="" selected="selected">Select State</option>
                        <option value="option1">Tamilnadu</option>
                        <option value="option2">Kerala</option>
                        <option value="option3">Karnataka</option>
                        <option value="option4">Maharastra</option>
                    </select>   
            </div>
            
            <div class="dropdcontent">
                <label>Select City:</label>
                    <select class="form-control" name ="SelectCity" id="select2">
                        <option value="option1">Select State</option>
                        <option value="option1">Chennai</option>
                        <option value="option1">Coimbatore</option>
                        <option value="option1">Madurai</option>
                        <option value="option2">Select State</option>
                        <option value="option2">Trivandrum</option>
                        <option value="option2">Kochi</option>
                        <option value="option2">Kollam</option>
                        <option value="option3">Select State</option>
                        <option value="option3">Bangalore</option>
                        <option value="option3">Mysore</option>
                        <option value="option4">Select State</option>
                        <option value="option4">Mumbai<option>
                        <option value="option4">Pune<option>
                  </select>     
            </div>
            <br/>
                    
            <button id="btn" type="submit">Submit</button>
            <input type="reset" value="RESET" onclick="clearreset()" name="reset" />    
        
    
        </form>
        <script src="formtoapi.js"></script>

formtoapi.cs :

document.getElementById("myForm").addEventListener("submit",submitForm);

function submitForm(event){
  event.preventDefault();
  var formData = new FormData(event.target);

  // Convert the FormData object to a JSON object
  var json = {};
  formData.forEach((value, key) => json[key] = value);

  fetch("https://localhost:7032/api/CarServiceForm/submit-form",{
    mode:"cors",
    method:"POST",
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(json)

  })
  .then(response =>{
    if(!response.ok){
      throw new Error("HTTP error"+response.status);
    }
    return response.json();
  })
  .then(data=>{
    console.log("Success:",data);
  })
  .catch(error=>{
    console.error("Error:",error);
  });
}

CarForm.cs : the model in API to which I trying to Post the form data

public class CarForm
    {
        public int Id { get; set; }
        public string CarModel { get; set; }
        public string CarNumber { get; set; }
        public string ContactNumber { get; set; }
        public string TypeOfService { get; set; }
        public string SelectedCheckboxes { get; set; }
        public string SelectState { get; set; }
        public string SelectCity { get; set; }
        public IList<Selection> ?Selections { get; set; }


    }

I’m able to post all the other input fields in Html form to api except SelectedCheckboxes[].
When I try to post , I get an error on the console regarding fetch as :

POST https://localhost:7032/api/CarServiceForm/submit-form 400
SelectedCheckboxes: ["The SelectedCheckboxes field is required."]
status: 400

Can Anyone tell me what goes wrong in the code

2

Answers


  1. You need to use

    formData.append(json[key], value)

    for appending all your checkbox value in formData and then pass it in your API call if API is only accepting in FormData

    Login or Signup to reply.
  2. This error message means the value of checkbox can’t be binded to the SelectedCheckboxes property successfully. From your comment, I think you want to achieve multiple selected, So you can change your code like:

    Model

     public string[] SelectedCheckboxes { get; set; }
    

    View

    <div class="check">
        
                    <label>Addons:</label>
                    <input type="checkbox"  value="10%off First service visit" id="10%off First service visit">
                    <label for="10%off First service visit">10%off First service visit</label>
                    <input type="checkbox"  value="10%off Waterwash" id="10%off Waterwash">
                    <label for="10%off Waterwash">10%off Waterwash</label>
                    <input type="checkbox"  value="Free AC Inspection" id="Free AC Inspection">
                    <label for="Free AC Inspection">Free AC Inspection</label>
    
                </div> 
    

    Js code

        //..........
        var json = {};
        formData.forEach((value, key) => json[key] = value);
       
        //add this code in your js
        let checkbox = document.querySelectorAll('input[type=checkbox]');
        let index = 0;
        let array = [];
    
        for (let i = 0; i < checkbox.length; i++)
        {
            if (checkbox[i].checked == true) {
                array.push(checkbox[i].value);
                index++
            }
        }
        json[`SelectedCheckboxes`] = array;
      
        //........
    

    Demo

    You can check when i select the first and the third checkbox, It can bind to SelectedCheckboxes successfully.

    SelectedCheckboxes

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search