Click here to Skip to main content
11,703,632 members (69,798 online)
Click here to Skip to main content

Simple JSON Handler for ASP.NET 2.0 to Implement AJAX Functionality

, 30 Jun 2011 CPOL 39.5K 1.4K 33
Rate this:
Please Sign up or sign in to vote.
Simple JSON handler for ASP.NET 2.0 to implement AJAX functionality

Introduction

This article describes how to use AJAX functionality using the popular JavaScript library (jQuery) with a minimal amount of code without using ASP.NET 2.0 AJAX tool kit. ASP.NET 2.0 does not support JSON so this will help if you want to use ASP.NET 2.0.

This example has two drop down controls for customer and customer description. Customer description will be loaded when customer drop down changes without reloading the entire page.

AJAX.JPG

Using the Code

AJAXProjectTree.JPG
  • JQuery library files need to be included to the project as shown above.

These are the library files:

  • jquery-1.4.1-vsdoc.js, jquery-1.4.1.js
  • query-1.4.1.min.js
  • jquery-1.5.2.min.js
  • jquery-ui-1.8.11.custom.min.js

Sample_ajax.js file will have Ajax implementation using JQuery.

var ajax = {

    setDebugMode: function(){
        this.debugMode = true;
    },

    get: function (requestUrl, data, loaderImageId, onSuccess, onComplete) {

        if (loaderImageId) {
            $("#" + loaderImageId).css('display', 'inline');
        }

        var completeFunction = function () {
            if (onComplete) {
                onComplete();
            }
            if (loaderImageId) {
                $("#" + loaderImageId).css('display', 'none');
            }
        };

        $.ajax({
            type: "GET",
            url: requestUrl,
            data: data,
            context: this,
            success: function (response) {
                onSuccess(response);
                completeFunction();
            },
            error: function (response) {
                alert("Ajax Request Failed");
                this.showError(response);
                completeFunction();
            }
        });
    },

    post: function (requestUrl, data, loaderImageId, onSuccess, onComplete) {

        if (loaderImageId) {
            $("#" + loaderImageId).css('display', 'inline');
        }

        var completeFunction = function () {
            if (onComplete) {
                onComplete();
            }
            if (loaderImageId) {
                $("#" + loaderImageId).css('display', 'none');
            }
        };

        $.ajax({
            type: "POST",
            url: requestUrl,
            context: this,
            data: data,
            success: function (response) {
                onSuccess(response);
                completeFunction();
            },
            error: function (response) {
                alert("Ajax Request Failed");
                this.showError(response);
                completeFunction();
            }
        });
    },

    showError: function(requestObject){
        if (this.debugMode){
            alert(requestObject.responseText);
        }
    }
};

ASPX Page (SampleAjax.aspx)

Include the JavaScript as below:

<script type="text/javascript" 
    src='<%= this.ResolveUrl("~/Scripts/jquery-1.5.2.min.js")%>' ></script>

Write JavaScript to call customer descriptions when customer drop down changes.

     <script type="text/javascript">
     <% if (SampleJSONWeb.ConfigurationData.DebugMode){ %>

LoadCustomerDescriptions.ashx will be invoked by the above JavaScript.

public class LoadCustomerDescriptions : JsonRequestHandler
{
    public override void ProcessRequest(HttpContext context)
    {
        string customerTypeId = context.Request.QueryString["customerTypeId"].ToString();

        //load data
        GetData getData = new GetData();
        IList<ReferenceData> data = getData.GetCustomerescriptions(customerTypeId);

        //Insert an empty row as the first row
        data.Insert(0, new ReferenceData(string.Empty, string.Empty));

        //return as JSON result
        Dictionary<string, string> response = new Dictionary<string, string>();
        response.Add("Data", GetJsonCollection<ReferenceData>(data));
        SetResponse(context, response);
    }
}  

The above method gets the data from the back end and sends back as JSON format. JSON handler has the implementation to manage JSON data as below:

using System;
using System.Collections.Generic;
using System.Web;
using System.Text;
using System.Reflection;
using System.Web.SessionState;

namespace SampleJSONWeb
{
    public abstract class JsonRequestHandler : IHttpHandler, IRequiresSessionState
    {

        public abstract void ProcessRequest(HttpContext context);

        protected void SetResponse(HttpContext context, string jsonResponse)
        {
            context.Response.Cache.SetExpires(DateTime.Now);
            context.Response.ContentType = "application/json";
            context.Response.Write(jsonResponse);
            context.Response.End();
        }

        protected void SetResponse(HttpContext context, 
			Dictionary<string, string> attributes)
        {
            SetResponse(context, GetJsonObject(attributes));
        }

        protected void SetResponse<T>(HttpContext context, T obj)
        {
            SetResponse(context, GetJsonObject<T>(obj));
        }

        protected T CreateObjectFromRequest<T>(HttpContext context) where T: new()
        {
            T ob = new T();
            PropertyInfo[] properties = typeof(T).GetProperties();
            foreach (PropertyInfo property in properties)
            {
                string value = context.Request.Params[property.Name];
                if (value == null)
                {
                    continue;
                }

                if (property.PropertyType != typeof(string) && value == string.Empty)
                {
                    continue;
                }

                object convertedValue = Convert.ChangeType(value, property.PropertyType);
                if (convertedValue == null)
                {
                    continue;
                }

                property.SetValue(ob, convertedValue, null);
            }
            return ob;
        }

        protected string GetJsonObject(Dictionary<string, string> attributes)
        {
            StringBuilder jsonBuilder = new StringBuilder();
            jsonBuilder.Append("{");
            bool firstTime = true;
            foreach (string key in attributes.Keys)
            {
                if (!firstTime)
                {
                    jsonBuilder.Append(",");
                }

                string name = key;
                object value = attributes[key];
                jsonBuilder.Append("\"" + name + "\":" + value.ToString());
                firstTime = false;
            }
            jsonBuilder.Append("}");
            return jsonBuilder.ToString();
        }

        protected string GetJsonCollection<T>(IEnumerable<T> collection)
        {
            StringBuilder jsonBuilder = new StringBuilder();
            jsonBuilder.Append("[");

            bool first = true;
            foreach (T item in collection)
            {
                if (!first)
                {
                    jsonBuilder.Append(",");
                }
                jsonBuilder.Append(GetJsonObject<T>(item));
                first = false;
            }

            jsonBuilder.Append("]");
            return jsonBuilder.ToString();
        }

        protected string GetJsonObject<T>(T obj)
        {
            PropertyInfo[] properties = typeof(T).GetProperties();
            StringBuilder jsonBuilder = new StringBuilder();
            jsonBuilder.Append("{");
            bool firstTime = true;
            foreach (PropertyInfo property in properties)
            {
                if (!firstTime)
                {
                    jsonBuilder.Append(",");
                }

                string name = property.Name;
                object value = property.GetValue(obj, null);
                jsonBuilder.Append("\"" + name + "\":\"" + value.ToString() + "\"");
                firstTime = false;
            }
            jsonBuilder.Append("}");
            return jsonBuilder.ToString();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}   

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Pubudu Kasakara
Architect
Singapore Singapore
Pubudu Kasakara is working as Solution Architect in Singapore. He has more than 11 years of professional involvement in the IT industry. Worked in successful projects involving mainly the Service Oriented Application by contributing to all requirements gathering, design and implementation phases. He is having experience with SOA applications development, Microsoft .NET, BizTalk, He is member of Charted It professional in UK.

Solution Architect
http://www.kasakara.com

You may also be interested in...

Comments and Discussions

 
QuestionIs there any third party tools which support JSON in asp.net 2.0. I have also mentioned my task below. Pin
manojnatarajan16-Oct-11 18:46
membermanojnatarajan16-Oct-11 18:46 
GeneralMy vote of 4 Pin
Hamlet Escaño1-Jul-11 10:26
memberHamlet Escaño1-Jul-11 10:26 
GeneralRe: My vote of 4 Pin
Pubudu Kasakara2-Jul-11 17:59
memberPubudu Kasakara2-Jul-11 17:59 
Generalgood article but implementation is complecated Pin
mike231515-Jun-11 3:58
membermike231515-Jun-11 3:58 
GeneralRe: good article but implementation is complecated Pin
Pubudu Kasakara30-Jun-11 23:19
memberPubudu Kasakara30-Jun-11 23:19 
GeneralMy Vote of 4 Pin
asp_crazy_guy14-Jun-11 23:01
memberasp_crazy_guy14-Jun-11 23:01 
GeneralMy vote of 5 Pin
Monjurul Habib14-Jun-11 11:14
memberMonjurul Habib14-Jun-11 11:14 
nice
GeneralLots of hoops... Pin
Onskee114-Jun-11 3:03
memberOnskee114-Jun-11 3:03 
GeneralRe: Lots of hoops... Pin
Pubudu Kasakara30-Jun-11 23:20
memberPubudu Kasakara30-Jun-11 23:20 
GeneralRe: Lots of hoops... Pin
Onskee11-Jul-11 8:16
memberOnskee11-Jul-11 8:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150819.1 | Last Updated 1 Jul 2011
Article Copyright 2011 by Pubudu Kasakara
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid