C# 如何序列化表单字段并将其发送到服务器jquery?
我在C# 如何序列化表单字段并将其发送到服务器jquery?,c#,javascript,jquery,C#,Javascript,Jquery,我在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="
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>
现在我的问题是:我正在使用jquery$.ajax方法提交表单。在服务器端,action方法接受产品
类数组。现在,我如何将表单字段转换为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()
您可以使用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();
您还可以使用jQuery++的formParams嗯。。。选择div,然后使用.map()返回使用div中输入值所期望的对象。
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
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();