5

(Question resolved with the help of the two reply posts--see below)

I would appreciate help getting a simple example of exchanging data JSON data between a browser (using JavaScript/JQuery) and ASP.NET (using Visual Studio 2010).

When I click a button the following is executed:

 <script type="text/javascript">
    bClick = function () {
        var myData = { "par": "smile" };
        alert("hi "+myData.par);
        $.ajax({
            url: "ericHandler.ashx",
            data: myData,
            dataType: 'json',
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            success: function (data) { alert("DIDit = " + data.eric); },
            error: function (data, status, jqXHR) { alert("FAILED:" + status); }
        });
    }
</script>

In Visual Studio, I have the following code associated with an ashx file. When I run it and click the button, everything works as expected except I don't see myData passed to the C# code--I am looking at context.Request.QueryString in the debugger and it shows "{}".

I have seen examples using

string stringParam = (string)Request.Form("stringParam");

but Visual Studio "Request" does not seem to be defined. All I want to do is see data move both ways, and I appear to be half way there. Any help would be appreciated.

--C# code--

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace CSASPNETSerializeJsonString
{
/// <summary>
/// Summary description for ericHandler
/// </summary>
public class ericHandler : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        string rq = context.Request.QueryString["par"];

        context.Response.ContentType = "application/json";
        context.Response.Write("{\"eric\":\"12345\"}");
    }

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

}

* RESOLVED First, if you want to send some form parameters from JavaScript to ASP.NET one should use the ajax call in the second post below and do NOT use stringify on the data. In other words, if don't specify the data being sent is json the lack of any specification defaults to 'application/x-www-form-urlencoded'). This will causes the object's fields to be appended in a "url" format (field=X&field2=Y&field3=Z..) and thus shows up in ASP.NET using Request.Form["field"].

Second, if you really do want to send JSON data, then specify this type is what is being sent (like I have done above) and use the InputStream on the receiving side. Further parsing of the received string is then required to get at the field values.

In my example, I am sending back JSON data having "manually" encoded it into a string. I believe there is a JSON serialization routine so that C# objects can be sent over.

Kiquenet
  • 14,494
  • 35
  • 148
  • 243
Eric Schneider
  • 51
  • 1
  • 1
  • 4

2 Answers2

5

Other resource suggest removing the contentType: 'application/json; charset=utf-8', from the AJAX call:

  $.ajax({ 
            url: "ericHandler.ashx", 
            data: myData, 
            dataType: 'json', 
            type: 'POST', 
            success: function (data) { alert("DIDit = " + data.eric); }, 
            error: function (data, status, jqXHR) { alert("FAILED:" + status); } 
        }); 

Read the values on the server side:

string myPar = context.Request.Form["par"]; 

You can also try:

string json = new StreamReader(context.Request.InputStream).ReadToEnd(); 

which was mentioned here: https://stackoverflow.com/a/8714375/139917

Community
  • 1
  • 1
DaveB
  • 9,470
  • 4
  • 39
  • 66
  • I tried what you suggested (stringify) but no change--In the receiving C# code, the variable rq is null and inspecting "context.Request.QueryString" shows an empty set "{}". Also, other examples don't use stringify--see http://stackoverflow.com/questions/5756147 – Eric Schneider Jun 29 '12 at 23:33
  • @EricSchneider - You are correct. jQuery does it for you. Since you are using the HTTP POST method. You need to access your values with Request.Form["myValue"]. I have edited my response. – DaveB Jun 30 '12 at 00:10
  • Using Request.Form did not help, BUT your second suggestion of using Request.InputStream worked! I get the serialized data generated by JavaScript. Of course, this now needs to be parsed, which perhaps is the root of the problem in that ASP.NET may not have a nice mapping from JSON to some data structure. – Eric Schneider Jun 30 '12 at 02:05
  • And finally, thanks so much! I spent hours pondering and searching this. I got the impression from various articles that ASP.NET had JSON support built-in, but I am not sure what this means now. ...Eric – Eric Schneider Jun 30 '12 at 02:07
  • One last comment, with the assignment "var myData = { "par":"smile", smart:345 };" in the JavaScript code, and using the prior mentioned Request.InputStream to fetch the passed data, if you don't use stringify prior to sending, you will receive par=smile&smart=345 whereas with stringify you receive,{"par":"smile", "smart":345}. – Eric Schneider Jun 30 '12 at 02:27
  • @EricSchneider - The JaaScript object needs to be converted to a JSON string to be sent. If you use the GET HTTP verb, the data is sent with the name/value pairs that you gave. With the POST method, the values are sent as part of the HTTP header. You might want to consider using a ASMX or WCF service instead of the ASHX handler as some of the serialization will be done by the framework. – DaveB Jun 30 '12 at 04:41
3

I got this working right away. This is its most basic form:

HTML:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>

    <script language="javascript" type="text/javascript">
        $(document).ready(function () {
            $.ajax({
                url: 'Handler.ashx',
                type: 'POST',
                success: function (data) {
                    alert(data);

                },
                error: function (data) {
                    alert("Error");
                }
            });
        });
    </script>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">

    </form>
</body>
</html>

Code Behind:

<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Web;

public class Handler : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        context.Response.Write("Hello World");
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}
Kiquenet
  • 14,494
  • 35
  • 148
  • 243
Hanlet Escaño
  • 17,114
  • 8
  • 52
  • 75
  • You example shows data being passed from ASP.NET to the browser, but the problem I am having is moving it in the other direction. Thus, the line that is failing is: "string rq = context.Request.QueryString["par"];"--I am trying to get myData's definition of "par" passed from the browser to ASP.NET. Any further thoughts (and thanks for your efforts so far!)? – Eric Schneider Jun 29 '12 at 23:36
  • Thanks! This was helpful--I'll put my summary up in my original post. ...Eric – Eric Schneider Jun 30 '12 at 02:33