Firstly, you will need to include latest jQuery .js file from the Google-hosted site. You can also host the jQuery file on your server, it’s all your choice. Now add a button tag, which trigger click event and send / post data to the generic handler.
# HTML Markup:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
First Name<input type="text" id="txtFirstName" /><br />
Last Name
<input type="text" id="txtLastName" /><br />
Qualification
<input type="text" id="txtQualication" /><br />
Age
<input type="text" id="txtAge" />
<button id="bntSubmit">Submit</button>
</body>
# Client-Side: Jquery- calling ajax on button click to send JSON data.
On button click, we calling ajax method, and send user data. i.e. First name, Last name, Qualification, and Age. You may notice in below client-side code under ajax method we have used `data: jsonData,` this is important here bcoz we are going to send / post JSON object on
You may notice in below client-side code under ajax method we have used `data: jsonData,` this is important here bcoz we are going to send / post JSON object on server. This is how our client side looks like.
$("#bntSubmit").on('click', function (e) {
// Initialize the object, before adding data to it.
// { } is declarative shorthand for new Object()
var obj = {};
obj.first_name = $("#txtFirstName").val();
obj.last_name = $("#txtLastName").val();
obj.qualification = $("#txtQualication").val();
obj.age = $("#txtAge").val();
//In order to proper pass a json string, you have to use function JSON.stringfy
var jsonData = JSON.stringify(obj);
$.ajax({
url: 'myGenericHandler.ashx',
type: 'POST',
data: jsonData,
success: function (data) {
console.log(data);
alert("Success :" + data);
},
error: function (errorText) {
alert("Wwoops something went wrong !");
}
});
e.preventDefault();
});
[ads_468_60]
# Add Generic Handler ( ashx file) in your Asp.net Application.
First, import those two namespaces as shown in below code.
//*
using System.Web.Script.Serialization;
using System.IO;
//*
Now we add a userInfo class into our generic handler ( ashx file ), which matches with our client side JSON object.
// we create a userinfo class to hold the JSON value
public class userInfo
{
public string first_name { get; set; }
public string last_name { get; set; }
public string qualification { get; set; }
public string age { get; set; }
}
This is our ProcessRequest method, where we retrieve parameter, data from client side ajax call.
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
try
{
string strJson = new StreamReader(context.Request.InputStream).ReadToEnd();
//deserialize the object
userInfo objUsr = Deserialize<userInfo>(strJson);
if (objUsr != null)
{
string fullName = objUsr.first_name + " " + objUsr.last_name;
string age = objUsr.age;
string qua = objUsr.qualification;
context.Response.Write(string.Format("Name :{0} , Age={1}, Qualification={2}", fullName, age, qua));
}
else
{
context.Response.Write("No Data");
}
}
catch (Exception ex)
{
context.Response.Write("Error :" + ex.Message);
}
}
Yeah, we are done now. Hit F5 and enjoy 🙂
Full Code of Generic Handler ( ashx file ).
<%@ WebHandler Language="C#" Class="myGenericHandler" %>
using System;
using System.Web;
using System.Web.Script.Serialization;
using System.IO;
public class myGenericHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
try
{
string strJson = new StreamReader(context.Request.InputStream).ReadToEnd();
//deserialize the object
userInfo objUsr = Deserialize<userInfo>(strJson);
if (objUsr != null)
{
string fullName = objUsr.first_name + " " + objUsr.last_name;
string age = objUsr.age;
string qua = objUsr.qualification;
context.Response.Write(string.Format("Name :{0} , Age={1}, Qualification={2}", fullName, age, qua));
}
else
{
context.Response.Write("No Data");
}
}
catch (Exception ex)
{
context.Response.Write("Error :" + ex.Message);
}
}
public bool IsReusable
{
get
{
return false;
}
}
// we create a userinfo class to hold the JSON value
public class userInfo
{
public string first_name { get; set; }
public string last_name { get; set; }
public string qualification { get; set; }
public string age { get; set; }
}
// Converts the specified JSON string to an object of type T
public T Deserialize<T>(string context)
{
string jsonData = context;
//cast to specified objectType
var obj = (T)new JavaScriptSerializer().Deserialize<T>(jsonData);
return obj;
}
}
You must check these article:
- Simple Asp.net C# webmethod call via jQuery Ajax JSON example.
- Chart.js + Asp.net: Create Pie chart with JSON response in Jquery.
- Easy way to upload Bulk Image in Asp.net C# using Dropzone JS.
- Preview Image before upload it with jQuery in Asp.net.
- Upload and Resize image using Dropzone Js in Asp.net.
Hope you enjoyed this tutorial. If you have any recommendations, please let us know what you think in the comment section below! See you again next time!
5 comments on “Generic Handler ashx file : Post send JSON data in Asp.net c#, jQuery”
this tutorial really bites man.
Hi,
Nice example. I get problem in casting to specified object type. The values are stored as null.
what could be the problem?
Thanks in advance
Very nice Sir…
Thankyou for This example, i am looking for it.
Very nice! Thank you. However, your jQuery gave me errors in Chrome, Edge. It only works in ie11. Any suggestion?
Also, the jQuery should be
success: function (jsondata) {
console.log(jsondata);
alert(“Success :” + jsondata);
data gave me the content of GenericHandler.ashx
Thank You! This solution is a very useful for me and Again Thank You.