结果显示为空

时间:2011-05-05 21:09:33

标签: ajax vb.net json jquery

我创建了一个 Customer JSON对象,其值如下所示:

{"Title":"Mr","FirstName":"S","LastName":"J","Birthday":"01/01/2011","Address":[{"Line1":"Line1","Line2":"Line2","City":"City","State":"State","Zip":"00000","County":"0000"},{"Line1":"Line11","Line2":"Line21","City":"City1","State":"State1","Zip":"11111","County":"1111"}],"Email":[{"Email":"s.j@sj.com","EmailType":"Personal"},{"Email":"s.j1@company.com","EmailType":"Work"}],"Phone":[{"Phone":"1231231234","PhoneType":"Mobile"},{"Phone":"1231232345","PhoneType":"Work"}]}

我需要在Handlers / CustomerHandler.ashx中获取这些数据来执行一些数据库操作。 我的AJAX调用如下:

  $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "Handlers/CustomerHandler.ashx",
        data: Customer,
        dataType: "json",
        success: insertCustomerCallback
    });

Dim customerJSON As String = HttpContext.Current.Request.Form("Customer")显示为空。

3 个答案:

答案 0 :(得分:2)

您可以使用json2.js中的JSON.stringify方法将客户作为JSON对象发送:

var Customer = { "Title": "Mr", "FirstName": "S", "LastName": "J", "Birthday": "01/01/2011", "Address": [{ "Line1": "Line1", "Line2": "Line2", "City": "City", "State": "State", "Zip": "00000", "County": "0000" }, { "Line1": "Line11", "Line2": "Line21", "City": "City1", "State": "State1", "Zip": "11111", "County": "1111"}], "Email": [{ "Email": "s.j@sj.com", "EmailType": "Personal" }, { "Email": "s.j1@company.com", "EmailType": "Work"}], "Phone": [{ "Phone": "1231231234", "PhoneType": "Mobile" }, { "Phone": "1231232345", "PhoneType": "Work"}] };
$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: "Handlers/CustomerHandler.ashx",
    data: JSON.stringify(Customer),
    dataType: "json",
    success: function (result) {

    }
});

并在通用处理程序上从请求流中读取它:

Dim customer = New Byte(context.Request.InputStream.Length - 1) {}
context.Request.InputStream.Read(customer, 0, customer.Length)
Dim customerJSON = Encoding.UTF8.GetString(customer)
// TODO: deserialize the JSON back to a Customer object

作为替代方案,您可以使用script enabled WebMethod

答案 1 :(得分:1)

我想我找到了它。 我必须按如下方式进行AJAX调用:

Customer = JSON.stringify(Customer);
$.ajax({
    type: "POST",
    contentType: "application/x-www-form-urlencoded",
    url: "Handlers/CustomerHandler.ashx?Operation=Insert",
    data: Customer,
    dataType: "json",
    success: insertCustomerCallback
});   

并使用以下代码获取数据

Dim customerJSON As String = HttpContext.Current.Request.Form(0).ToString()

谢谢, Sharmin

答案 2 :(得分:0)

您可以考虑使用ASMX“ScriptService”而不是原始的HttpHandler。使用ScriptService有the handy benefit of automatically deserializing JSON input to .NET objects,看起来它在您的场景中会有所帮助。