Search code examples
jqueryasp.netjtemplates

jQuery and jTemplates - how to get the proper values?


I have problems constructing the right format of a jTemplates - hoping for some help. This is what I have: an ASP.NET page with a WebMethod. This WebMethod returns data to jQuery. The data should then be processed by jTemplates, but I am unsure of the format for the jTemplate.

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data.Common;
using System.Web.Services;
using System.Linq;
using System.Web.Script.Services;

public partial class jpaging : System.Web.UI.Page
{
    [WebMethod]
    public static IEnumerable PagingData(int Page, int PageSize)
    {
        // talk to database and return datatable
        Database db = DatabaseFactory.CreateDatabase();
        using (DbCommand cmd = db.GetStoredProcCommand("Paging"))
        {
            db.AddParameter(cmd, "@Page", DbType.Int32, 4, ParameterDirection.Input, true, 10, 0, null, DataRowVersion.Default, Page);
            db.AddParameter(cmd, "@PageSize", DbType.Int32, 4, ParameterDirection.Input, true, 10, 0, null, DataRowVersion.Default, PageSize);
            using (DataTable dt = (db.ExecuteDataSet(cmd)).Tables[0])
            {
                var t = from data in dt.AsEnumerable() select data.ItemArray;
                return t;
            }
        }
    }
}

Data returned from "return t" is in the following format.

{"d":[
 [1,1,"First 1","Last 1",301],
 [2,2,"First 2","Last 2",301],
 [3,3,"First 3","Last 3",301],
 [4,4,"First 4","Last 4",301],
 [5,5,"First 5","Last 5",301],
 [6,6,"First 6","Last 6",301],
 [7,7,"First 7","Last 7",301],
 [8,8,"First 8","Last 8",301],
 [9,9,"First 9","Last 9",301],
 [10,10,"First 10","Last 10",301]
]}

I am using the following code to parse the data to jTemplates:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="jpaging.aspx.cs" Inherits="jpaging" EnableViewState="false" %>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="paging/jquery-jtemplates.js" type="text/javascript"></script>
<script type="text/javascript">

var currentPage = 1;
var pageSize = 10;

$(document).ready(function () {
   loadData(1); 
});

function loadData(page) {
   currentPage = page;
   $.ajax({
       type: "POST",
       url: "jpaging.aspx/PagingData",
       data: "{'Page':'" + page + "', 'PageSize':'" + pageSize + "'}",
       contentType: "application/json; charset=utf-8",
       dataType: "json",
       success: function (msg) {
           doTemplating(msg); 
           // ....
       }
   });
}

function doTemplating(msg) {
    $('#cont').setTemplateURL('/mytemplate.htm', null, { filter_data: false });
    $('#cont').processTemplate(msg);
}

</script>
</head>
<body>

   <table id="rsstable" cellspacing="0">
    <thead>
       <tr><th>ID</th><th>First</th><th>Last</th></tr>
    </thead>
    <tbody id="cont"></tbody>
   </table>

</body>
</html>

I am unsure how mytemplate.htm should be constructed:

{#foreach $T.d as post}
<tr>      
  <td> <-- what to write here for column1? --> </td>
  <td> <-- what to write here for column2? --> </td>
  <td> <-- what to write here for column3? --> </td>
</tr>
{#/for}

I have tried with something like {$T.post[0]} but that does not work.

As a side note I want to avoid returning something like this from the WebMethod:

    var feeds = from feed in dt.AsEnumerable()
            select new
            {
                EmployeeID = feed["EmployeeID"],
                FirstName = feed["FirstName"],
                LastName = feed["LastName"],
                Total = feed["TotalRows"]
            };
     return feeds;

If that was the case I would just do something like this:

{#foreach $T.d as post}
<tr>
  <td>{$T.post.EmployeeID}</td>
  <td>{$T.post.FirstName}</td>
  <td>{$T.post.LastName}</td>
</tr>
{#/for}

...but I want to avoid this to make the template more generic/usable for other returned data.

Any suggestions? :-)


Solution

  • I am unsure of where JSONP fits into what you are doing? JSONP only supports the GET HTTP action, ie not POST. See here: Post data to JsonP

    You can do cross domain posts with CORS, see here: http://enable-cors.org/

    I would recommend either using firebug and using a debug point to inspect your return variable or use this style of logging: How can I display a JavaScript object? . That will allow you to see what is being returned. After that, you can then narrow your issue to being specifically to do with JTemplate. You could alternatively try the templating built into jquery called jquery.tmpl http://api.jquery.com/jquery.tmpl/