I have a form in HTML
which contains multiple same name fields. For example:
<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 model class Product
:
//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 am submitting the form using jquery $.ajax method
. On the server side the action method accepts a Product
class array. Now how can I convert the form fields into a Json
array (similar to product array). I tried:
$("#form").serialize();
&
$("#form").serializeArray();
The first generates the name-value pair of all the form fields and the second generates the name-value array of all the form fields. And my requirement is:
//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 anyone tell me how can I can achieve this through JavaScript
or JQuery
?
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With