通过AJAX将多个JSON对象传递给ASP.Net PageMethod

时间:2018-01-24 10:05:21

标签: javascript asp.net json ajax

我试图通过AJAX将两个JSON对象传递给我的Page方法

我在Code Behind中创建了一个类,并在javascript中创建了一个JSON对象数组。

以下是我的两个班级和Page Method

public class userModel
{
    public string userid { get; set; }
    public string Name { get; set; }
}
public class companyModel 
{
    public string companyid { get; set; }
    public string Name { get; set; }
}
[WebMethod]
public static string TestJsonMethod(userModel[] users)
{

    return "";
}

以下是我的Javascript

function TestJSON() {
        //var JSONObject = { a: [], b };
        var obj = {users: []};
        var user;
        for (var i = 0; i < 3; i++) {
            user = {
                userid: i.toString(),
                Name: "User" + i.toString() 
            }
            obj.users.push(user);
        }

        var company = {companyid: "4", Name:"TEST COMPANY"};

        $.ajax({
            url: "bulkconsignments.aspx/TestJsonMethod",
            type: "POST",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(obj),
            async: false,
            cache: false,
            success: function (msg) {
                alert(msg.d);
            }
        });
    }

到目前为止,我的代码工作正常。

我想要做的是将公司对象传递给Page方法,就像这样

[WebMethod]
public static string TestJsonMethod(userModel[] users, companyModel company)
{

    return "";
}

2 个答案:

答案 0 :(得分:1)

您可以将模型合并为一个模型。

public class TestJsonModel
{
    public UserModel UserModel { get; set; }

    public CompanyModel CompanyModel { get; set; }
}

然后行动看起来像;

[WebMethod]
public static string TestJsonMethod(TestJsonModel model)

此外,Ajax请求发布数据看起来像;

data: JSON.stringify({UserModel:obj,CompanyModel:company})

答案 1 :(得分:0)

我正在尝试不同的方式来做这件事。

function TestJSON() {
    //var JSONObject = { a: [], b };
    var obj = {users: [], company: {}};
    var user;
    for (var i = 0; i < 3; i++) {
        user = {
            userid: i.toString(),
            Name: "User" + i.toString() 
        }
        obj.users.push(user);
    }


    var company_ = {companyid: "4", Name:"TEST COMPANY"};
    obj.company = company_;
    $.ajax({
        url: "bulkconsignments.aspx/TestJsonMethod",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(obj),
        async: false,
        cache: false,
        success: function (msg) {
            alert(msg.d);
        }
    });
}

页面方法背后的代码保持不变。

 [WebMethod]
public static string TestJsonMethod(userModel[] users, companyModel company)
{

    return "";
}