【问题标题】:MVC submit form outside ajax.beginformMVC 在 ajax.beginform 之外提交表单
【发布时间】:2012-07-05 11:26:05
【问题描述】:

我有一个特定的 ajax 表单,提交时我想在该 ajax 表单之外包含另一个表单。让我给你举个例子:

    @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 表单一起提交其他东西?

【问题讨论】:

    标签: ajax asp.net-mvc-3 razor


    【解决方案1】:

    我不认为 MS 不显眼的 AJAX 支持这一点。所以让我们摆脱它并使用普通的jQuery。 .serialize() 方法是您正在寻找的。

    因此,我们首先将 Ajax.BeginForm 表单替换为常规的 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>
    }
    

    然后我们为另一个表单提供一个 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 个具有相同名称的元素),否则默认模型绑定器可能会发疯。如果有任何冲突,由您来解决。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-29
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 2011-05-27
      • 2011-09-07
      • 1970-01-01
      相关资源
      最近更新 更多