我在HTML
中有一个表单,其中包含多个相同的名称字段。例如:
<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>
现在在服务器端(C#),我有一个操作方法和一个模型类
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; }
}
现在我的问题是:我正在使用
jquery $.ajax method
提交表单。在服务器端,action方法接受Product
类数组。现在如何将表单字段转换为Json
数组(类似于产品数组)。我试过了: $("#form").serialize();
&
$("#form").serializeArray();
第一个生成所有表单字段的名称/值对,第二个生成所有表单字段的名称/值数组。我的要求是:
//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" }
]
谁能告诉我如何通过
JavaScript
或JQuery
实现这一目标? 最佳答案
您可以使用map
方法。
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/
关于c# - 如何序列化表单字段并将其发送到服务器,jQuery?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13076001/