HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Making a simple call to a server

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
servercallmakingsimple

Problem

Earlier this year, before I learnt about Code Review Stack Exchange, I gave this answer in response to a question about how to combine ASP.NET, jQuery, and JSON:

I keep thinking that there must be a better way to handle the JSON than just using escaped string literals, but I'd like to know for sure.

urlToHandler = 'handler.ashx';
jsonData = '{ "dateStamp":"2010/01/01", "stringParam": "hello" }';
$.ajax({
                url: urlToHandler,
                data: jsonData,
                dataType: 'json',
                type: 'POST',
                contentType: 'application/json',
                success: function(data) {                        
                    setAutocompleteData(data.responseDateTime);
                },
                error: function(data, status, jqXHR) {                        
                    alert('There was an error.');
                }
            }); // end $.ajax

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class handler : IHttpHandler , System.Web.SessionState.IReadOnlySessionState
{
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "application/json";

        DateTime dateStamp = DateTime.Parse((string)Request.Form["dateStamp"]);
        string stringParam = (string)Request.Form["stringParam"];

        // Your logic here

        string json = "{ \"responseDateTime\": \"hello hello there!\" }";
        context.Response.Write(json);    
    }

Solution

You are correct. There is a better way. Starting in .NET 3.5, there is a JavaScriptSerializer class that can be used for simplifying JSON responses. It can be found in the System.Web.Script.Serialization namespace (System.Web.Extensions assembly)

First, you'd need to make a model to represent your response:

public class SimpleResponse {
    public string responseDateTime { get; set; }

    public SimpleResponse() {
          responseDateTime = "hello hello there!";
    }
}


...Then in your handler:

public void ProcessRequest(HttpContext context)
 {
     context.Response.ContentType = "application/json";
     var json = new JavaScriptSerializer();

     context.Response.Write(
         json.Serialize(new SimpleResponse())
     );    
 }


Here is the result:

{"responseDateTime":"hello hello there!"}


In an ASP.NET MVC application this is more trivial. Just return a JsonResult from your controller:

public JsonResult Index()
{
    return Json(new SimpleResponse());
}

Code Snippets

public class SimpleResponse {
    public string responseDateTime { get; set; }

    public SimpleResponse() {
          responseDateTime = "hello hello there!";
    }
}
public void ProcessRequest(HttpContext context)
 {
     context.Response.ContentType = "application/json";
     var json = new JavaScriptSerializer();

     context.Response.Write(
         json.Serialize(new SimpleResponse())
     );    
 }
{"responseDateTime":"hello hello there!"}
public JsonResult Index()
{
    return Json(new SimpleResponse());
}

Context

StackExchange Code Review Q#3208, answer score: 8

Revisions (0)

No revisions yet.