如何序列化表单字段并将其发送到服务器,jquery?

时间:2012-10-25 19:42:01

标签: 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="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" }
   ]

有谁能告诉我如何通过JavaScriptJQuery实现这一目标?

3 个答案:

答案 0 :(得分:1)

您可以使用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/

答案 1 :(得分:0)

如果是这种情况,您可以使用.map()

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

答案 2 :(得分:0)

您还可以使用jQuery ++的formParams http://jquerypp.com/#formparams