IMG-LOGO

How to post JSON string to generic Handler using JQUery in ASP.Net C#?

andy - 12 Aug, 2013 34185 Views 0 Comment

In this tutorial you will learn how easily you can post json string using jquery to generic handler (ashx file) in C# asp.net. Firstly, you will need to import jquery framework from Google hosted site. You can host the jquery file in your server if you preffered.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>

In this example, we will send a basic user information containing Name, Email and Contact No. You can copy the following html code if you want. Note: as we are using div tags rather than table, it is recommended that you copy the css styles as well.

<div class="row">
	<div class="rowlabel">Name:</div>
	<div class="rowinput"><input type="text" id="txtName" value="" /></div>
	<div class="clear"></div>
</div>

<div class="row">
	<div class="rowlabel">Email:</div>
	<div class="rowinput"><input type="text" id="txtEmail" value="" /></div>
	<div class="clear"></div>
</div>

<div class="row">
	<div class="rowlabel">Contact No:</div>
	<div class="rowinput"><input type="text" id="txtContactNo" value="" /></div>
	<div class="clear"></div>
</div>

<div class="row">
	<div class="rowlabel nobg">&#160;</div>
	<div class="rowinput"><input type="button" id="btnSubmitJSON" value="Submit" class="submitbutton"/></div>
	<div class="clear"></div>
</div>
<div id="output"></div>

Those are the stylesheet codes.

<style type="text/css">
	.row{
		padding-bottom:5px;
		display:block;
		clear:both;
	}
		
	.rowlabel{
		float:left;
		width:110px;
		background:#1a66b5;
		padding:5px 10px;
		color:#fff;
		text-align:right;
	}
		
	.rowinput{
		float:left;
		margin-left:10px;
		width:220px;
	}
		
	.rowinput input{
		width:200px;
		height:30px;
		line-height:30px;
		border:solid 1px #ccc;
		border-radius:5px;
	}
		
	.nobg{
		background:none;
	}
		
	.submitbutton{
		cursor:pointer;
	}
		
	.submitbutton:hover{
		background:#2636d1;
		color:#fff;
	}
		
	.clear{
		clear:both;
	}
</style>

The next one is the javascript code that will perform some basic functions. We have included the comment codes so you can read further what the codes do.

<script type="text/javascript">
	$(function () {
		//we bind the submit click function
		$("#btnSubmitJSON").click(function(){
			var nameValue = $("#txtName").val();
			var emailValue = $("#txtEmail").val();
			var contactValue = $("#txtContactNo").val();

			//we just use a quick check if the value are empty or not
			if(nameValue != "" && emailValue != "" && contactValue != ""){
				//we can hide the button just to make sure user does not click the button during the progress.
				$("#btnSubmitJSON").show();

				//we can output ajax icon loading so the user know it is in progress.
				$("#output").html("<img src=\"/content/images/ajax-loader.gif\" /> Please wait, we are processing your request.");

				//we build the json string
				var jsonData = {
					'Name': nameValue,
					'Email': emailValue,
					'Contact': contactValue
				}

				//note in order to proper pass a json string, you have to use function JSON.stringfy
				jsonData = JSON.stringify(jsonData);

				$.ajax({
					url: "/ContactHandler.ashx", //make sure the path is correct
					cache: false,
					type: 'POST',
					data: jsonData,
					success: function (response) {
						//output the response from server
						$("#output").html(response);

						//we clean up the data
						$("#txtName").val("");
						$("#txtEmail").val("");
						$("#txtContactNo").val("");
					},
					error: function (xhr, ajaxOptions, thrownError) {
						$("#output").html(xhr.responseText);
						$("#btnSubmitJSON").show();
					}
				})
			}else{
				$("#output").html("Please enter all fields.");
			}
		});
	});
</script>

These are the behind codes of Generic Handler file. Make sure System.IO and System.Web.Script.Serialization namespaces are included.

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

using System;
using System.Web;
using System.IO;
using System.Web.Script.Serialization;

public class ContactHandler : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
		//set the content type, you can either return plain text, html text, or json or other type    
		context.Response.ContentType = "text/plain";

		//deserialize the object
		UserInfo objUser = Deserialize<UserInfo>(context);
		
		//now we print out the value, we check if it is null or not
		if (objUser != null) {
			context.Response.Write(String.Format("You have entered Name: {0}, Email: {1}, Contact: {2}", objUser.Name, objUser.Email, objUser.Contact));
		} else {
			context.Response.Write("Sorry something goes wrong.");
		}
    }

	/// <summary>
	/// This function will take httpcontext object and will read the input stream
	/// It will use the built in JavascriptSerializer framework to deserialize object based given T object type value
	/// </summary>
	/// <typeparam name="T"></typeparam>
	/// <param name="context"></param>
	/// <returns></returns>
	public T Deserialize<T>(HttpContext context) {
		//read the json string
		string jsonData = new StreamReader(context.Request.InputStream).ReadToEnd();

		//cast to specified objectType
		var obj = (T)new JavaScriptSerializer().Deserialize<T>(jsonData);

		//return the object
		return obj;
	}
	
	// we create a class object to hold the JSON value
	public class UserInfo{
		public string Name { get; set; }
		public string Email { get; set; }
		public string Contact { get; set; }
	}
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}

Demo C# ASP.Net JSON Jquery Post Example

This is the demo on how it will work. Simply enter all values for those fields. Note: it only check for empty values only.

Name:
Email:
Contact No:
 

Comments

There are no comments available.

Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.

Related Articles

How to remove html tags from string in c#?

Sometimes you need to remove HTML tags from string to ensure there are no dangerous or malicious scripts especially when you want to store the string or data text into the database.