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 ?
source share