2017-07-03 25 views
0

我有一個從提交將發送項目值到ASHX文件使用JSON。我希望這個ASHX文件採用JSON字符串並遍歷每個項目。我已經將這些放置在一個包含項目對象的項目對象中。有幾篇關於Stack Overflow的文章,描述瞭如何「反序列化」一個數組並將其添加到自定義類中,但是,我不確定這是如何發生的。你能不能請我描述一下,好像我五歲?使用AJAX發送JSON時,如何從ASHX文件返回JSON屬性?

$.ajax({ 
       url: 'addItems.ashx', 
       data: JSON.stringify({items: objectArray }), 
       method: 'POST', 
       dataType: 'JSON', 
       contentType: "application/json; charset=utf-8", 
       success: function (data) { 
        console.log(data.responseText); 
       }, 
       error: function (data) { 
        console.log(data.responseText); 
       } 
      }); 

樣品JSON:

{"items":[{"qty":"374","description":"Non repellendus Illum voluptate ea eu tempora eaque maiores quaerat corrupti rerum distinctio Omnis voluptatem","capAsset":"2","iuTag":""},{"qty":"374","description":"Non repellendus Illum voluptate ea eu tempora eaque maiores quaerat corrupti rerum distinctio Omnis voluptatem","capAsset":"2","iuTag":""}]}

ASHX文件:

public class items 
{ 
    public string description { get; set; } 
    public string iuTag { get; set; } 
    public int capAsset { get; set; } 
    public int qty { get; set; } 
} 

public class addItems : IHttpHandler 
{ 

    public void ProcessRequest(HttpContext context) 
    { 
     string connectionString = ConfigurationManager.ConnectionStrings["SurplusConnectionString"].ConnectionString.ToString(); 
     SqlConnection con = new SqlConnection(connectionString); 
     context.Response.ContentType = "application/json";   
     JavaScriptSerializer json_serializer = new JavaScriptSerializer(); 
     string json = new StreamReader(context.Request.InputStream).ReadToEnd(); 
     var items = JsonConvert.DeserializeObject<items>(json);    

    } 
    public bool IsReusable 
    { 
     get 
     { 
      return false; 
     } 
    } 

回答

0

你接近 - 你現在需要做的就是使用您作爲參數的HttpContext輸出寫入到響應:

context.Response.Write(jsonString); 

而且我會添加相應的頭文件爲好,以表明你正在返回JSON

context.Response.Headers.Add("Content-Type","application/json")); 

語法可能有點關閉,但這就是主意。