将Javascript对象数组传递给C#代码背后

Pass Javascript Array of Objects to C# Codebehind

本文关键字:代码 背后 Javascript 对象 数组      更新时间:2023-09-26

我在将对象的Javascript数组发布到C#代码背后时遇到了一些问题。我遵循了一个简单的教程,认为这会很好地工作,但我在PassThings中的C#代码绑定断点从未被命中。

我已经尝试将url更改为"Default.aspx/PassThings",但它仍然不会被发布到我的代码后面,错误警报显示"[object object"]

这是我的客户端:

默认.aspx

脚本

<script>
    function Save() {
        $(document).ready(function () {
            var things = [
        { id: 1, color: 'yellow' },
        { id: 2, color: 'blue' },
        { id: 3, color: 'red' }
        ];
                things = JSON.stringify({ 'things': things });
                $.ajax({
                    contentType: 'application/json; charset=utf-8',
                    dataType: 'json',
                    type: 'POST',
                    url: '/PassThings',
                    data: things,
                    success: function () {
                        alert("success");
                    },
                    error: function (response) {
                        alert(response);
                    }
                });
            });
    }
</script>

Html

<input type="button" value="Pass Things" onclick="JavaScript: Save();">

默认.aspx.cs

编码后

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Web.Services;
[System.Web.Script.Services.ScriptService]
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    [WebMethod]
    public void PassThings(List<Thing> things)
    {
        var t = things;
    }
    public class Thing
    {
        public int Id { get; set; }
        public string Color { get; set; }
    }
}

有人看到我做错了什么吗?

谢谢你抽出时间。

url中,将正确的url与页面一起传递。假设PassThings方法在Default.aspx页面代码隐藏文件中,那么如果脚本代码是在Default.aspx中编写的,则必须传递url:Default.aspx/PassThings

如果脚本在Scripts文件夹中的单独js文件中,那么您必须返回一个目录,并必须写入:url:/Default.aspx/PassThings

$(document).ready(function () {
    var things = [{
        id: 1,
        color: 'yellow'
    }, {
        id: 2,
        color: 'blue'
    }, {
        id: 3,
        color: 'red'
    }];
    things = JSON.stringify({
        'things': things
    });
    $.ajax({
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        type: 'POST',
        url: 'Default.aspx/PassThings',
        data: things,
        success: function () {
            alert("success");
        },
        error: function (response) {
            alert(JSON.stringify(response));
        }
    });
});

并且在你的方法后面的代码中应该用[WebMethod]装饰,它应该是publicstatic:

    [WebMethod]
    public static void PassThings(List<Thing> things)
    {
        var t = things;
    }