1

我有一个特定的 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 表单一起提交?

4

1 回答 1

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 个具有相同名称的元素),否则默认模型绑定器可能会发疯。如果有任何冲突,由你来解决。

于 2012-07-05T11:41:41.660 回答