Sending raw JSON request to ASP.NET from JQuery

JSON or Javascript Object Notation has been quite popular these days because of being it is only a Key/Value pair, but also can significantly form a Tree structure of data. For small and precise Ajax communication, people are preferring JSON over XML or html because it is portable and very small in size.

JQuery being one of the most favorite Javascript library these days, provide better syntaxes that allows the developer to create javascript code more concise. With the growing use of JSON and JQuery, people often want to combine both of them to create a seamless environment that is fast and small both, and make use of the power of javascript better than ever. JQuery Ajax has always been the developers choice nowadays to send and receive requests to the server. The super simple api provided by Jquery gives the developer an edge to deal with things easier.

While working with JQuery Ajax requests with ASP.NET, I was looking to send only the data that I need to send to the server and parse them back to the server side and save it to the database. As my requirement is so damn simple, I tried to send JSON AJAX request to the server and deserialize it there.

Let us take few steps to send raw JSON object from Javascipt to server using JQuery.

Step 1:

Create a class in the ASP.NET project or any class library associated with it and name it as SaveData.cs. We implement the SaveData class from IHttpHandler and implemented both IsReusable and ProcessRequest.

Step 2:

Add the HTTPHandler to the Web.Config. You can also use ashx in this case to define the handler. (It is worth notifying, you can also add an ASHX template handler in the same way)


<httpHandlers>
<add verb="*" path="Save.ashx" type="MyProject.SaveData"/>
</httpHandlers>

Step 3:

From javascript make a JQuery AJAX request and send the data to the SaveData handler.

var strJson = JSON.stringify(JsonDetails);
$.ajax({
url: 'Save.ashx',
type: 'post',
async: false,
contentType: 'application/json; charset=utf-8',
data: strJson,
dataType: 'json',
success: function (result) {
alert('success');
},
error: function (result) {
alert('failed');
}
});

Say here the JSON object that I need to send to the server as data is stored into JsonDetails object. We use JSON.stringify to convert the JSON object into a string and send it to AJAX. Notice, the AJAX has been configured to post the data to the Request body and send the data. The dataType of the AJAX request is configured as Json.

Once this is done, the browser will can now call the IHttpHandler that we have created before with only the raw JSON data into its body.

Step 4:

As the request sent to the handler is in raw format, you cannot find the parameters into the Request context. Even though ASP.NET provides superior API to deal with context, it fails to parse the raw JSON object automatically in most of the cases. To parse the json request, you need to parse it yourself.

public class SaveData : IHttpHandler
{
public bool IsReusable
{
get { return true; }
}

public void ProcessRequest(HttpContext context)
{
var jsonString = String.Empty;

context.Request.InputStream.Position = 0;
using (var inputStream = new StreamReader(context.Request.InputStream))
{
jsonString = inputStream.ReadToEnd();
}

JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
object serJsonDetails = javaScriptSerializer.Deserialize(jsonString, typeof(object));

// You can now add logic to work with serJsonDetails object

}

You are done. If you run the project and call the AJAx request form the Javascript, the data would be easily parsed in the server and you will get the actual JSON object.

I hope you like this post, and am confident that this will help you a lot.

Abhishek Sur

Abhishek Sur is a Microsoft MVP since year 2011. He is an architect in the .NET platform. He has profound theoretical insight and years of hands on experience in different .NET products and languages. He leads the Microsoft User Group in Kolkata named KolkataGeeks, and regularly organizes events and seminars in various places for spreading .NET awareness. He is associated with the Microsoft Insider list on WPF and C#, and is in constant touch with product group teams. He blogs at http://www.abhisheksur.com His Book : Visual Studio 2012 and .NET 4.5 Expert Development Cookbook. Follow Abhishek at Twitter : @abhi2434

One Comment to “Sending raw JSON request to ASP.NET from JQuery”

Comments are closed.