Generic Handler ashx file : Post send JSON data in Asp.net c#, jQuery

/ / 4 Comments

Jquery ajax, post data t generic handler :  Here in this tutorial will explain how easily we can post or send  JSON string ( data ) using jQuery to the generic handler ( ashx file) in Asp.net, C#. In another word How we can send parameters, data to Generic handler (ashx) file using jquery ajax (client side). You can also check my previous article on Asp.net, C#, jQuery, JSON  and  jQuery Ajax JSON Example in Asp.net with sql database

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


# 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:

Thank you for reading, pls keep visiting this blog and share this in your network. Also, I would love to hear your opinions down in the comments.

PS: If you found this content valuable and want to thank me? 👳 Buy Me a Coffee

Subscribe to our newsletter

Get the latest and greatest from Codepedia delivered straight to your inbox.


Post Comment

Your email address will not be published. Required fields are marked *

4 Comments

  1. Purvesh Patel 12/02/2015 14:14:45
    Thank You! This solution is a very useful for me and Again Thank You.
  2. Ashish 06/29/2017 05:54:53
    Very nice Sir... Thankyou for This example, i am looking for it.
  3. Rani 02/26/2018 01:48:43
    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
  4. dong 03/29/2018 18:42:13
    this tutorial really bites man.