Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Working with JsonHTTPHandler

5.00/5 (2 votes)
13 Nov 2010CPOL1 min read 15.3K   34  
This article gets you started with JsonHTTPHandler for nicer code.

Introduction


This article helps you to understand how to get data from ordinary .NET classes to Json Object.



Background


I was working with handlers, but I used .ashx files but when I had to do many functions the code became a little hard to read. So I found this JsonHTTPHandler (http://code.google.com/p/jsonhandlerdotnet/) that made my life easyer.



Using the Code


First, you need to download the DLL here.



  1. You have to add the reference that you just downloaded.
  2. Then you have to add this in web.config
  3. Then you need to add this in your global.asax


<configuration>
   <system.web>  
     <httpHandlers>
        <add verb="*" path="*.json" type="JsonHTTPHandler.JSONHandler, JsonHTTPHandler" /> </httpHandlers> </system.web> </configuration> 


C#
void Application_Start(object sender, EventArgs e)
        {
            // Code that runs on application startup
            JSONHandler.RegisterService(typeof(HandlerClass));
        }


Now you are really set to go and here is what I have done.


Here is my code for my class.



C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using JsonHTTPHandler;
namespace Json.Model
{
    [JsonService]
    public class HandlerClass
    {
        /// <summary>
        /// Just a simple test
        /// </summary>
        /// <returns>a string </returns>
        [JsonMethod]
        public Result JsonTest()
        {
            Result result = new Result();
            result.result = "From Object to Json";
            return result;
        }
        /// <summary>
        /// This is a simple search method for users.
        /// </summary>
        /// <returns></returns>
        [JsonMethod]
        public List<User> Filter(string searchStr)
        {
            List<User> users = GetUsers();
            var result = (from u in users where u.UserName.Contains(searchStr) select u).ToList();
            return result;
        }
        /// <summary>
        /// Gets a list of the users
        /// </summary>
        /// <returns></returns>
        [JsonMethod]
        public List<User> GetUsers()
        {
            List<User> users = new List<User>();
            for(int i =1;i<10;i++)
            {
                User user = new User();
                user.UserName = "Adam" + i;
                user.Email = "adam"+i+"@site"+i+".com";
                user.Website = "http://www.site"+i+".com";
                users.Add(user);   
            }
            
            return users; 
        }
    }
    public class Result
    {
        public string result { get; set; }
    }
}


As you can see, I have added some attributes to define the class and the method.


I have made some result objects as well, one of them is in the HandlerClass called Result. And I have made a simple User object as well.



C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Json.Model
{
    public class User
    {
        public string UserName { get; set; }
        public string Email { get; set; }
        public string Website { get; set; }
    }
}


Well when you add the reference JsonHTTPHandler, you should also add Newtonsoft.Json that comes with it. This assembly allows you to serilize C# objects to Json and that's the beauty of it.


I have added the Jquery library and made some jquery functions.


Here is my JavaScript:


JavaScript
$(document).ready(function(){
    LoadTestScript();
});
function LoadTestScript(){
    $.getJSON("/.json/HandlerClass/JsonTest",
         function (data) {
             $("#Test").text(data.result);
             
         });
}
function getUsers() {
    $("#anv").find("li").remove();
    $.getJSON("/.json/HandlerClass/GetUsers",
         function (data) {
             $.each(data, function (i) {
                 $("#anv").append("<li>" + data[i].UserName + "</li>");
             });
        });
}
function getUsersWithParams() {
    var searchStr = $("#search").val();
    $("#anvSearch").find("li").remove();
    $.getJSON("/.json/HandlerClass/Filter",
    { "searchStr": searchStr },
         function (data) {
             $.each(data, function (i) {
                 $("#anvSearch").append("<li>" + data[i].UserName + "</li>");
             });
             
         });
}


On page load, I'll load the test method.


Here is my code for the default page.


HTML
<h2>
        Welcome to a sweeter world.
    </h2>
    <p>
        Prints out data from the class JsonTest()<br />
        <div id="Test"></div>
    </p>
    <p><a href="#" onclick="getUsers();">Load users</a></p>
    <p>
        <div>
        <ul id="anv">
        
        </ul>
        </div>
    </p>
    <p><input type="text" id="search" value="Adam1" /><a href="#" onclick="getUsersWithParams();">Search Users</a></p>
    <p>
        <div>
        <ul id="anvSearch">
        
        </ul>
        </div>
    </p>


As you can see, it's quite simple.


You can easily browse to the methods like this: http://localhost/.json/<Your Class Name>/<Your Method>


and if you use parameters, you just add the ordinary query like this: http://localhost/.json/<Your Class Name>/<Your Method>?<Your parameter Name>=<Your parameter value>


I really think this is cool. You can have a better control on your code.

License

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