2012-07-05 180 views
1

之外我有一定的Ajax表单并提交时,我想包括AJAX形式之外的另一种形式。让我告诉你一个例子:MVC提交表单ajax.beginform

@using (Ajax.BeginForm("PayWithBankTransfer", "Payment", new { salesLineId = salesLine.SalesLineID }, new AjaxOptions 
                                { 
                                 HttpMethod = "POST", 
                                 UpdateTargetId = "bankForm", 
                                 LoadingElementId = "spinnerBank" 
                                }, new { id = "feedback-form" })) 
{ 
    //some stuff 
    <button type="submit">Reserve</button> 
} 

我有另一个标记的形式之外我想在Ajax表单提交包括

<div id="theOtherStuff"> 
    //otherStuff 
</div> 

我怎么能与AJAX一起提交其他的东西形成?

回答

1

我不认为MS不显眼的AJAX支持此功能。所以让我们摆脱它,并使用普通的jQuery。 .serialize()方法就是你要找的。

所以我们开始用一个普通Html.BeginForm

@using (Html.BeginForm(
    "PayWithBankTransfer", 
    "Payment", 
    new { salesLineId = salesLine.SalesLineID }, 
    FormMethod.Post, 
    new { id = "feedback-form" }) 
) 
{ 
    //some stuff 
    <button type="submit" class="t-button t-state-default" style="width: 100px; height: 50px;">Reserver</button> 
} 

更换Ajax.BeginForm形式,然后我们提供一个ID,其他形式的,这样我们就可以在脚本中引用它:

<div id="theOtherStuff"> 
    @using (Html.BeginForm(null, null, FormMethod.Post, new { id = "theOtherStuffForm" })) 
    { 
     //otherStuff 
    } 
</div> 

和所有剩下的就是写我们的脚本在一个单独的JavaScript文件,悄悄地AJAXify这种形式:

$(function() { 
    $('#feedback-form').submit(function() { 
     $('#spinnerBank').show(); 
     $.ajax({ 
      url: this.action, 
      type: this.method, 
      data: $(this).add('#theOtherStuffForm').serialize(), 
      success: function (result) { 
       $('#bankForm').html(result); 
      }, 
      complete: function() { 
       $('#spinnerBank').hide(); 
      } 
     }); 

     return false; 
    }); 
}); 

以下行应特别关注:

data: $(this).add('#theOtherStuffForm').serialize(), 

正如你可以看到.serialize方法允许多种形式转换为适合序列化形式。

,你不应该有冲突的名字用的2种形式的输入元素(例如有2个元素具有相同的名称),否则默认模型绑定可以去疯抢它比更为明显。如果有任何问题,请由您来解决这些冲突。

+0

谢谢@DarinDimitrov这似乎是做伎俩:) – gardarvalur 2012-07-05 12:47:07