2014-11-14 184 views
1

正嘗試通過Ajax,我無法在處理程序JSON數據發送到ASP.NET HTTP處理程序

這裏來檢索JSON數據JSON數據發送到HTTP處理程序是我的代碼發送JSON數據

功能SendJsonData( ){

 var Jsonstring = "[{ AssetName: 'ANA001', AssetNumber: 'ANU001',SerialNumber:'S001',RFIDTag:'R001'},{ AssetName: 'ANA002', AssetNumber: 'ANU002',SerialNumber:'S002',RFIDTag:'R002'},{ AssetName: 'ANA003', AssetNumber: 'ANU003',SerialNumber:'S003',RFIDTag:'R003'}]"; 

     var myJSON = JSON.stringify(Jsonstring); 
     $.ajax({ 
      async: true, 
      contentType: 'application/json; charset=utf-8', 
      dataType: 'json', 
      type: "POST", 
      data: myJSON , 
      dataType: "json", 
      contentType: "application/json; charset=utf-8", 
      url: "http://localhost:58275/NFCDataHandlerData.ashx", 
      // url: "http://166.78.189.76:93/NFCDataHandlerData.ashx",     
      success: function (response) { 
       alert(response.d); 
      } 
     }); 
    } 

這是我的把手的代碼,我想這樣的方法,但我沒有得到JSON數據

public void ProcessRequest(HttpContext context) 
    { 
     //context.Response.ContentType = "application/json"; 
     //var data = context.Request; 
     //var sr = new StreamReader(data.InputStream); 
     //var stream = sr.ReadToEnd(); 
     //   var serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); 
     //var jsonObject = serializer.DeserializeObject(stream); 

     //string objectdata = jsonObject.ToString(); 
     //string Jsondata = string.Empty; 

     //if (HttpContext.Current.Request["Jsondata"] != null) 
     //{ 
     // Jsondata = HttpContext.Current.Request["Jsondata"]; 
     //} 

     string json1 = HttpContext.Current.Request.Form["json"]; 

     string objectdata = string.Empty; 

     if (HttpContext.Current.Request["Jsonstring"] != null) 
     { 
      objectdata = HttpContext.Current.Request["Jsonstring"]; 
     } 

     JavaScriptSerializer json = new JavaScriptSerializer(); 

     List<NFCAssetData> myObjs = new List<NFCAssetData>(); 
     myObjs = json.Deserialize<List<NFCAssetData>>(objectdata); 

感謝您的幫助。

回答

5

準備有效的數據

// either from object 
var myJSON = JSON.stringify([{ AssetName: 'ANA001', AssetNumber: 'ANU001'}]) 
// or from valid JSON string 
var myJSON = '[{"AssetName":"ANA001","AssetNumber":"ANU001"}]' 

你現在有什麼是JSON編碼字符串無效JSON。

和服務器端應該是這樣的

var request = context.Request; 
var requestBody = new StreamReader(request.InputStream, request.ContentEncoding).ReadToEnd(); 
var jsonSerializer = new JavaScriptSerializer(); 
var data = jsonSerializer.Deserialize<List<NFCAssetData>>(requestBody);