Tom*_*der 5 javascript c# 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="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>
Run Code Online (Sandbox Code Playgroud)
现在在服务器端(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; }
}
Run Code Online (Sandbox Code Playgroud)
现在我的问题是:我正在使用提交表单jquery $.ajax method.在服务器端,action方法接受一个Product类数组.现在我如何将表单字段转换为Json数组(类似于产品数组).我试过了:
$("#form").serialize();
&
$("#form").serializeArray();
Run Code Online (Sandbox Code Playgroud)
第一个生成所有表单字段的名称 - 值对,第二个生成所有表单字段的名称 - 值数组.我的要求是:
//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" }
]
Run Code Online (Sandbox Code Playgroud)
任何人都可以告诉我如何通过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();
Run Code Online (Sandbox Code Playgroud)