How to serialize form fields and send them to jquery server?

I have a form in HTML that contains several identical name fields. For instance:

  <form action="" method="post" id="form"> <div class="itemsection" id="item1"> <input type="text" name="Price" /> <input type="text" name="Name" /> <input type="text" name="Catagory" /> </div> <div class="itemsection" id="item2"> <input type="text" name="Price" /> <input type="text" name="Product" /> <input type="text" name="Catagory" /> </div> <div class="itemsection" id="item3"> <input type="text" name="Price" /> <input type="text" name="Product" /> <input type="text" name="Catagory" /> </div> </form> 

Now on the server side (C #), I have an action method and a class for the Product model:

  //Action method accepts the form on server //It require the Product array public ActionResult SaveItem(Product[] products) { ..... ... } //Model class product public Class Product { public int Id { get; set; } public double Price { get; set; } public string Name { get; set; } public string Catagory { get; set; } } 

Now my question is: I submit the form using the jquery $.ajax method . On the server side, the action method takes an array of Product . Now, how can I convert form fields to a Json array (similar to an array of products). I tried:

  $("#form").serialize(); & $("#form").serializeArray(); 

The first generates a name-value pair of all form fields, and the second generates an array of values ​​by the name of all form fields. And my requirement:

  //currently my form contains 3 item section so : [ { "Price" : "value", "Name" : "value", "Catagory" : "value" }, { "Price" : "value", "Name" : "value", "Catagory" : "value" } { "Price" : "value", "Name" : "value", "Catagory" : "value" } ] 

Can someone tell me how can I achieve this via JavaScript or JQuery ?

+4
source share
3 answers

You can use the map method.

 var data = $('.itemsection').map(function(){ return { Price: $('input[name="Price"]', this).val(), Product: $('input[name="Product"]', this).val(), Category: $('input[name="Category"]', this).val() } }).get(); 

http://jsfiddle.net/KRJJ7/

+1
source

If in this case you can use .map()

 var arr = $('form :input').map(function() { return { 'Price' : $(this).attr('Price') , 'Name' : $(this).attr('Name') , 'Category' : $(this).attr('Category') , } }).get(); // get() will convert them into an array 
0
source

You can also use jQuery ++ formParams http://jquerypp.com/#formparams

0
source

Source: https://habr.com/ru/post/1442159/


All Articles