29 July 2013

Using HttpHandler and Consuming it with JQuery/AJAX

I had this very simple example to create your own HttpHandler (Generic Handler) and consume it in your page using JQuery/Ajax:

 
    public class MyHandler : IHttpHandler
    {
        private HttpContext _myContext;

        public void ProcessRequest(HttpContext context)
        {
            _myContext = context;

            _myContext.Response.ContentType = "text/html";

            KampungList();
        }

        public void KampungList()
        {
            _myContext.Response.Write("<p>This is viewed from handler. Today's date and time is " + DateTime.Now + ". </p>");
       
        }

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


To consume it, simply create the following JavaScript in your page

 <script type="text/javascript">
        $.ajax({
            type: "GET",
            url: "MyHandler.ashx",
            cache: false,
            success: function (html) {
                $("#handleme").append(html);
            }
        });
  </script>


I know it's too simple but I hope newbies out there could learn something from it.

No comments:

Post a Comment