Download sample for here
Last few days ago, I was woking with HTTP handler. Here I was required to call handler from Client script. Later I found, that I need to pass some data to handler and also recieve some from it.
So I was looking for if there is some way we can pass some data to handler in some format and can recieve.
So Here I am going to share, How we can call a HTTPHandler from jQuery and can pass some data to handler and receive as well.
So Let’s go step by step
- First create a HTTP Handler say “MyHandler.ashx” and put your logic there
- As we are using jQuery here. So include the jQuery script in your aspx page
- Now write the script to call your Handler at your aspx page in javascript block or write it in a separate script file and include it in your page.
- OnSucessfull complete of your request receive the data and process it as required.
Now lets see the example:
I have created one Website type application and included the jQuery library in my application. Now first lets see , how to call HTTP handler.
function CallHandler() { $.ajax({ url: "Handler/MyHandler.ashx", contentType: "application/json; charset=utf-8", success: OnComplete, error: OnFail }); return false; }
Here url is the url of your Handler. contentType defines the content of the request. On successful completion of the request the OnComplete method will be called. If there is any error of the request the OnFail will be called. The dummy methods are
function OnComplete(result) { alert('Success'); } function OnFail(result) { alert('Request failed'); }
Now we can call this CallHandler method from any event. For the demo, I have called this on a button click as
Now what you’ll do if you need to pass some data to your handler. For this you can add one more parameter data in you call. Here you need to give data in form of Name value parameter as
data: { 'Id': '100002','Type': 'Employee'} // Now the updated method as function CallHandler() { $.ajax({ url: "Handler/MyHandler.ashx", contentType: "application/json; charset=utf-8", data: { 'Id': '10000', 'Type': 'Employee' }, success: OnComplete, error: OnFail }); return false; }
Now you can access the data in handler’s ProcessRequest method as
string Id = context.Request["Id"]; string type = context.Request["Type"];
Now, If you want to receive data from Handler at Client side. How will you move ahead.
It’s very easy to return data in JSON format.
Here in my sample example, I have created one Class Employee and returning it from handler after serializing with the help of JavaScriptSerializer. My Class is as.
public class Employee { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } public string Department { get; set; } }
Now let’s see the handler part. I am sending the Id of employee from Client
public class MyHandler : IHttpHandler { public void ProcessRequest (HttpContext context) { var employee = GetData(Convert.ToInt32(context.Request["Id"])); //Do the operation as required JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); string serEmployee = javaScriptSerializer.Serialize(employee); context.Response.ContentType = "text/html";\ context.Response.Write(serEmployee); } public bool IsReusable { get { return false; } } private Employee GetData(int Id) { var employee = new Employee(); employee.Id = Id; employee.Name = "Brij"; employee.Age = 27; employee.Department = "Research and Development"; //Write your logic here return employee; } }
Now the CallHanler method will be as
function CallHandler() { $.ajax({ url: "Handler/MyHandler.ashx", contentType: "application/json; charset=utf-8", dataType: "json", data: { 'Id': '10000' }, responseType: "json", success: OnComplete, error: OnFail }); return false; } function OnComplete(result) { alert([result.Id, result.Name, result.Age, result.Department]); } function OnFail(result) { alert('Request Failed'); }
Now you can receive the data and use it as per your requirement at client side. Above here I have just shown as alert popup.
I think this post will help you a lot. As this can be used at different scenarios. The classic example could be.
“In many situation, we get the task to upload files in our applications with lots of validation it could validations like file type, content size and some business validations as well. All these validations could not be handled at Client side only. One approach could be HTTPHandler which we can use for seamless validations.”
Thanks a lot to all of you.
Cheers,
Brij
Pingback: Using jQuery to consume an ASP.NET Ashx from JSON in two files « O2Platform.com for Developers
Thanks this was very useful
FYI, I’ve referenced you here: http://o2platform.wordpress.com/2011/07/12/using-jquery-to-consume-an-asp-net-ashx-from-json-in-two-files/
Thanks dude!!
How can we pass data values dynamically
Hi, i’ve noticed that if you set type=’POST’ in your $.ajax function, the server does not receive the parameters (parameter ‘Id’ in your example) unless you comment contentType argument. Do you know why is that?, or if there is another way to solve this?
Thanks in advance.
We can have two types Get or Post. Default is Get. In Get data is posted in URL. where is Post it is sent in message body.
For details, Have a look here
http://stackoverflow.com/questions/715335/get-vs-post-in-ajax
Hi Brij,
Thanks of the tip. You are sending a key value pair here. What about an array?
Can you pl show how to covert gridview data into JSON array and send it to HTTP handler using jquery-ajax? Also how to fill a gridview using an array returned from .ashx file using jquery and ajax
thanks
ben
You can easily pass the json in string format. The Idea is data should be in string format. This can be achieved by JSON.stringify . Later you can use JavaScriptSerializer to deserialize it at server side.
I am not sure, what do you mean by gridview data. There must some datasource that is getting bind to gridview.
Say if you have some List of object, that can be easily converted JSON string. You can serialise it via JavaScriptSerializer and at Client side convert it using JSON.Parse method
You can send data from Client to Server using jQuery Ajax but if you want to send from Server to Client then you can use hiddenfield or some callback approach.
Also I am not able to understand why you are using ashx file to fill gridview. It’s better to use AJAX or Client Callback.
You can have a look to my below Article that deals a lot JavaScript arrays and passing it back and fourth to the server.
http://www.codeproject.com/Articles/125724/Client-Templating-with-jQuery
Hi Brij
Thanks again.
Initially the gridview is getting bound by a datasource. The client then enters data in textfields provided in the gridview. Then update the data using jquery-ajax, without page reload. So basically, i want to convert the data in the gridview (or say a table) to an array(JSON) and send it to server for updation. I am using ashx file just to avoid overheads and improve speed. How to convert data from gridview to JSON array – the procedure, is where i am stuck. I’ll just go through the link.
ben
Excellent stuff!
Thanks Ratul
works very good for me. Greatly appreciate it.
Glad to know that it helped you.
Cheers,
Brij
Hi, Your code is not working. Also your sample link is broken
Thanks for pointing it out about the link. The URL must have got updated. I have updated the link.
And the code should explained should work, there must be some issue. Please see the sample.
Thanks,
Brij
Thanks a bunch man. Your tutorial helped me a lot
Thanks rohan!! Glad that you find it useful
Nice article
It’s really useful. thanks.
Nice Article
Great job dude
Thanks friend!!