Send JSON data to ASP.NET HTTP Handler

3.4k views Asked by At

Am trying to send JSON data to HTTP handler through ajax am unable to retrieve JSON data at Handler

Here is my code to send json data

function 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);
            }
        });
    }

This is my handle code which i tried like these methods but am not getting JSON data

 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);

Thanks for the help .

1

There are 1 answers

0
Leonid On BEST ANSWER

Prepare valid data

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

What you have now is JSON-encoded string with invalid JSON.

And server-side should look like this

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