Efficient Ajax with .NET
July 2, 2010 Leave a comment
This technology post was written by Jorge Cotillo, one of our engineers in Peru who is also a .NET expert.
I use AJAX with .NET to create highly interactive experiences for users in almost all the projects I’ve been working on, but sometimes using AJAX can be a really problem. Here I will show you a really simple and efficient way to accomplish this kind of implementation using HttpHandlers!
Using HttpHandlers helps you to centralize all your AJAX calls to a Server Side methods, returning a Json Serialization of a entire Business Object(B.O), a Generic List of Business Objects or you can return a whole rendered Html page just by calling RenderControl() method of a UserControl called from an HttpHandler class.
At this point maybe you are wondering, when I should use this RenderControl() method and an HttpHandler class? Well the answer is simple!
- You want to have the server side to do all the effort to render a page instead of making the client side to render Html tags from a Json Serialization
- You want to reduce the server response
Talking more about the second point I can say that, sometimes maybe you want to use only one or two properties from a Business Object and returning it using Json will serialize the entire object. This means that it will return some properties that maybe you don’t want to use increasing the server response (if you want to avoid this you can use a DTO – Data Transfer Object but that is a topic for another blog entry).
It is really simple to use an HttpHandler, you can just create a Generic Handler class (*.ashx) or just create any class (*.cs) and implement IHttpHandler interface with ProcessRequest method an IsReusable property. If you implement this interface or you are using your Generic Handler class and you are rendering a user control you can do the following:
Then in your web.config you need to configure something like this: (at httpHandlers section)
<add verb=”GET” path=”Page.aspx” type=”Namespace, App_Code”/> (add App_Code if you are working in VS .NET 2005)