5

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 methodProductサーバー側では、アクション メソッドはクラス配列を受け入れます。フォームフィールドを配列に変換するにはどうすればよいですかJson(製品配列に似ています)。私は試した:

   $("#form").serialize();  
           &
   $("#form").serializeArray();

1 つ目はすべてのフォーム フィールドの名前と値のペアを生成し、2 つ目はすべてのフォーム フィールドの名前と値の配列を生成します。そして私の要件は次のとおりです。

  //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?

4

3 に答える 3

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/

于 2012-10-25T19:48:50.583 に答える
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
于 2012-10-25T19:45:36.900 に答える
0

jQuery++ の formParams http://jquerypp.com/#formparamsも使用できます。

于 2012-10-25T19:51:29.553 に答える