在asp.net中发送复杂数据和JSON问题

时间:2011-08-31 13:52:17

标签: javascript asp.net json

我正在尝试使用jquery将复杂的数据结构发布到我的服务器端方法。

这里我给的是我的c#类结构

public partial class SerializeJSON : System.Web.UI.Page
{

    [System.Web.Services.WebMethod]
    public static string GetData(List<Customer> oCust)
    {
        int empid = oCust[0].EmpID;
        string name = oCust[0].Name.ToString();
        DateTime dob = oCust[0].BirthDate;
        double sal = oCust[0].Salary;
        Address add = oCust[0].Address[0];
        return "";
    }
}

public class Customer
{
     List<Address> add = null;
     public Customer()
     {
         add = new List<Address>();
     }

    public int EmpID { get; set; }
    public string Name { get; set; }
    public DateTime BirthDate { get; set; }

    public List<Address> Address
    {
        get { return add; }
        set { add = value; }
    }
    public double Salary { get; set; }
}

public class Address
{
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string PostCode { get; set; }
}

我知道json的样子是什么样的。正确的json将是

[
{
    "EmpID":1,
    "Name":"Keith",
    "BirthDate":"\/Date(947874600000)\/",
    "Address":[{"Address1":"Salt lake","Address2":"Kolkata","PostCode":"784512"}],"Salary":5200
}

这里我告诉你如何将数据实际从我的客户端发送到服务器端 这是我的javascript代码,我在客户端填充数据,最近我发送这个像

 var Person = {};
    Person["EmpID"] = 1;
    Person["Name"] = "Keith";
    Person["BirthDate"] = "08/15/2011";

    var Address = {};
    Address["Address1"] = "Salt lake";
    Address["Address2"] = "Kolkata";
    Address["PostCode"] = "741258";

    Person["Address"] = Address;

$(function () {
        $('#btnSubmit').click(function () {
            alert(JSON.stringify(Person));
            $.ajax({
                type: "POST",
                url: "SerializeJSON.aspx/GetData",
                data: "{'oCust':'" + JSON.stringify(Person) + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                }
                ,
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert(textStatus);
                }
            });
            return false;
        });
    });

但我收到了错误。 JSON.stringify()没有生成正确的json。 所以请告诉我填充和放置的最佳方法是什么?以编程方式生成正确的json数据。有一件事我需要说,我不想手动生成json,而是告诉我以编程方式生成正确的json。

所以指导我如何使用javascript以编程方式生成正确的json。

也告诉我使用javascript填充数据的方法是错误的。

 var Person = {};
    Person["EmpID"] = 1;
    Person["Name"] = "Keith";
    Person["BirthDate"] = "08/15/2011";

    var Address = {};
    Address["Address1"] = "Salt lake";
    Address["Address2"] = "Kolkata";
    Address["PostCode"] = "741258";

    Person["Address"] = Address;

上面的代码是错误的方法。

所以请指导我如何使用javascript生成正确的json,可以在服务器端轻松反序列化。感谢

这里我根据naveen重构我的代码

var Persons = [];

var Person = {};     人[“EmpID”] = 1;     人[“姓名”] =“基思”;     人[“BirthDate”] =“08/15/2011”;

var Address = []; var addr = {};     addr [“Address1”] =“盐湖”;     addr [“Address2”] =“加尔各答”;     addr [“PostCode”] =“741258”;     Address.push(ADDR);

Person["Address"] = Address;
Persons.push(Person)

var DTO = {oCust:Persons} data:JSON.stringify(DTO)

我希望它现在能够发挥作用......不是吗?

var Persons = [];

var Person = {};     人[“EmpID”] = 1;     人[“姓名”] =“基思”;     人[“BirthDate”] =“08/15/2011”;

var Address = []; var addr = {};     addr [“Address1”] =“盐湖”;     addr [“Address2”] =“加尔各答”;     addr [“PostCode”] =“741258”;     Address.push(ADDR);

Person["Address"] = Address;

var DTO = {oCust:Person} data:JSON.stringify(DTO)

我是对的吗?

如果我的班级结构如下

public partial class SerializeJSON:System.Web.UI.Page     {

    [System.Web.Services.WebMethod]
    public static string GetData(Customer oCust)
    {
        int empid = oCust.EmpID;
        string name = oCust.Name.ToString();
        DateTime dob = oCust.BirthDate;
        double sal = oCust.Salary;
        Address add = oCust.Address[0];
        return "";
    }
}

public class Customer
{
     List<Address> add = null;
     public Customer()
     {
         add = new List<Address>();
     }

    public int EmpID { get; set; }
    public string Name { get; set; }
    public DateTime BirthDate { get; set; }

    public List<Address> Address
    {
        get { return add; }
        set { add = value; }
    }
    public double Salary { get; set; }
}

public class Address
{
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string PostCode { get; set; }
}

然后我的json看起来像

1 个答案:

答案 0 :(得分:5)

这是使用WebMethod自动反序列化复杂JSON的片段 如果有疑问,请仔细阅读评论。

public class Customer
{
    public int EmpID { get; set; }
    public string Name { get; set; }
    public DateTime BirthDate { get; set; }

    // why did you use the conventional get set in this case?
    // feel free to revert if you are using the class elsewhere. 
    public List<Address> Address { get; set; }
    public double Salary { get; set; }
}

public class Address
{
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string PostCode { get; set; }
}

的WebMethod

[System.Web.Services.WebMethod]
public static string GetData(Customer oCust)
{
    try
    {
        int empid = oCust.EmpID;
        string name = oCust.Name.ToString();
        DateTime dob = oCust.BirthDate;
        double sal = oCust.Salary;
        Address add = oCust.Address[0];
        return "Success";
    }
    catch (Exception exception)
    {
        //Elmah.ErrorSignal.FromCurrentContext().Raise(exception);
        return "Failed";
    }
}

AJAX致电

$(function () {
    $('#btnSubmit').click(function (evt) {
        var Person = {};
        Person["EmpID"] = 1;
        Person["Name"] = "Keith";
        //converting to date is not mandatory, but its more typesafe
        Person["BirthDate"] = new Date("08/15/2011");

        var Address = [];
        var addr = {};
        addr["Address1"] = "Salt lake";
        addr["Address2"] = "Kolkata";
        addr["PostCode"] = "741258";
        Address.push(addr);

        Person["Address"] = Address;

        var DTO = { oCust: Person }
        //save yourself some typing. dataType and charset in content type are not needed.
        //Courtesy: http://encosia.com/save-yourself-some-typing-when-you-call-asp-net-services/
        $.ajax({
            type: "POST",
            url: "SerializeJSON.aspx/GetData",
            data: JSON.stringify(DTO),
            contentType: "application/json",
            success: function (msg) {
                //ASP.NET 2.0 fallback.
                var data = msg.hasOwnProperty("d") ? msg.d : msg;
                //place a div with id=content to show the result.(not mandatory)
                $("#content").hide().html(msg.d).delay(1000).show(400);
            },
            error: function (xhr, textStatus, errorThrown) {
                //you should ideally call the xhr.responseText to see the error
                alert(xhr.responseText);
            }
        });
        evt.preventDefault();
    });
});

HTML

<div id="content"></div>
<asp:Button ID="btnSubmit" runat="server" Text="Submit"/>

希望这有帮助。