Tuesday, June 21, 2011

Jquery template sample

First I will add a generic handler to my asp.net website like below and then create a new page to use jquery ajax to call the httphandler and then using jquery template to show the data.
<%@ WebHandler Language="C#" Class="PersonHandler" %>

using System;
using System.Web;
using System.Collections.Generic;
using System.Runtime.Serialization.Json;
using System.IO;

public class PersonHandler : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {

        //If method is POST
        //string name = context.Request.Form["name"];
        
        //If method is GET
        //string name = context.Request.QueryString["name"];
        
        List<Person> list = new List<Person>();
        list.Add(new Person() { ID = 1, Name = "abc" });
        list.Add(new Person() { ID = 2, Name = "xcv" });
        list.Add(new Person() { ID = 3, Name = "klp" });

        string str = "";
        DataContractJsonSerializer serilizer = new DataContractJsonSerializer(typeof(List<Person>));
        using (MemoryStream ms = new MemoryStream())
        {
            serilizer.WriteObject(ms, list);
            ms.Position = 0;
            StreamReader sr = new StreamReader(ms);
            str = sr.ReadToEnd();
            sr.Dispose();
        }
        
        context.Response.ContentType = "application/json";
        context.Response.Write(str);
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }
}

public class Person
{
    public int ID { get; set; }
    public string Name { get; set; }
}

<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.1.min.js" type="text/javascript"></script>
        <script src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js" type="text/javascript"></script>
       <script type="text/javascript">
           $(document).ready(function () {

               $("#btnLoad").click(function () {

                   $.ajax({
                       type: "POST",
                       data: {"name":"ssss"},
                       url: "PersonHandler.ashx",
                       //contentType: "application/json; charset=utf-8",
                       contentType: "application/x-www-form-urlencoded", // should be like this for httphandler to work
                       dataType: "json",
                       success: function (msg) {
                           if (msg.d == null)
                               Process(msg);
                           else
                               Process(msg.d);
                       },
                       error: function (e) {
                           alert("failed");
                       }

                   });
               });

           });
function Process(data) {
    //var data = [{ Name: "abc", ID: 1 }, { Name: "def", ID: 2 }, { Name: "ghi", ID: 3}];

    //compile the template
    $.template("tmp", $("#mytmpl"));

    //render the compiled template
    $.tmpl("tmp", data).appendTo("#container");
}
           
  </script>
 
 <script id="mytmpl" type="text/html">
    <li>${Name} , ${ID}</li>
</script>
 
</head>
 
<body>
 
 <input type="button" id="btnLoad" value="Load Data" />

<ul id="container"></ul>
 
</body>
</html>

0 comments:

Post a Comment