如何使用ajax在asp.net中发布表单数据

Mur*_*ain 2 asp.net jquery

我想使用ajax发布asp.net的表单数据。并希望在另一页上以表单数组的形式接收该数据。

这是我现在要做的 Default2.aspx

 $('#btnSubmit').click(function () {
            $.ajax({
                type: "POST",
                url: "Default3.aspx",
                data:  $('#form1'),
                success: function (msg) {
                    alert("Success");
                }
            });
        });
Run Code Online (Sandbox Code Playgroud)

并在 Default3.aspx

 protected void Page_Load(object sender, EventArgs e)
    {

        int loop1;
        NameValueCollection coll;

        //Load Form variables into NameValueCollection variable.

        coll = Request.Form;
        // Get names of all forms into a string array.
        String[] arr1 = coll.AllKeys;
        for (   loop1 = 0; loop1 < arr1.Length; loop1++)
        {
            Response.Write("Form: " + arr1[loop1] + "<br>");
            Label1.Text = arr1[loop1];
        }

    }
Run Code Online (Sandbox Code Playgroud)

更新:我正在通过 ajax 调用发送序列化对象。我想在我的 asp.net 代码中使用这些数据。我怎样才能做到这一点 ?

jga*_*fin 5

使用serialize方法。

由于您使用的是表单,您可以让它控制如何发布帖子:

var $frm = $('#form1');
$('input[type="submit]', $frm).click(function (e) {
    e.preventDefault();

    $.ajax({
        type: $frm.attr('method'),
        url: $frm.attr('action'),
        data:  $frm.serialize(),
        success: function (msg) {
            alert("Success");
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

可以将其重构为可以放置在母版页中的通用脚本:

<script type="text-javascript">
    $(function() {
        $('.post-using-ajax').each(function() {
            var $frm = $(this);
            $frm.submit(function (e) {
                e.preventDefault();

                $.ajax({
                    type: $frm.attr('method'),
                    url: $frm.attr('action'),
                    data:  $frm.serialize(),
                    success: function (msg) {
                        alert("Success");
                    }
                });
            });
        });
    });
</script>
Run Code Online (Sandbox Code Playgroud)

这让您可以将所有带有 CSS 类的post-using-ajax表单转换为 AJAX 表单。

<form method="POST" action="someAction" class="post-using-ajax">
    <!-- all form items -->
</form>
Run Code Online (Sandbox Code Playgroud)