Denny.NET

I can haz ASP.NET goodness?

About the author

Denny Ferrassoli
Developer at Casting Networks. MCP / .NET
E-mail me Send mail
Add to Technorati Favorites

Recent comments

Authors

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2008

Passing a JSON object to a WCF service with jQuery

[Updated: 04/25/08] 

This example uses WCF to create a service endpoint that will be accessible via an ASP.NET page with jQuery/AJAX. We will use AJAX to pass a JSON object from the client-side to the webservice. We will only use jQuery to connect to the web service, there will be no ASP.NET AJAX library used. Why no ASP.NET AJAX library? jQuery is already included in the project and it can handle all the necessary AJAX calls and functionality that we would want if we were using the ASP.NET AJAX script library. We're also going to save  about 80kb of overhead (much more if in debug mode) by excluding the ASP.NET AJAX library. This is in no way saying that the ASP.NET AJAX library isn't useful... As a matter of fact if we were to do the same example with the library we could save ourselves from writing extra code. However the point of this example is to show that we can access the web service even if we don't have a nicely generated client-side proxy a la ASP.NET AJAX.

The WCF Service:

I'm going to start by adding an AJAX-enabled WCF Service to a Website. (Make sure you're running the correct version of .NET - I am using 3.5 here)

After adding the service it opens up to the service's code-behind file. Go ahead and browse around the file for a second.

The first thing I'm going to point out is to make sure that the "AspNetCompatibilityRequirements" is set to "Allowed":

[code:c#]
[AspNetCompatibilityRequirements( RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed )]
[/code]

This attribute indicates that our service should run in ASP.NET compatibility mode. If it were not "Allowed" we would not be able to access the service from ASP.NET. This attribute is automatically generated when you add the "AJAX-enabled WCF Service." For a detailed explanation of the attribute go to MSDN.

Looking at the generated code-behind file we can see it has placed a "DoWork()" method with the "OperationContract" attribute. This is created by default but lets keep it since we will be using this method to run this example. One thing we want to add is a "WebGet" attribute and set the "RequestFormat" to "Json." WebGet associates the operation with a UriTemplate (not discussed in this example) as well as the GET verb. Setting the RequestFormat allows us to define that the Request should be in JSON format. Our "DoWork()" method should now look like this:

[code:c#]
[OperationContract]
[WebGet( RequestFormat=WebMessageFormat.Json )]
public void DoWork()
{
 // Add your operation implementation here
 return;
}
[/code]



The Data/Object Structure:

We want to pass in a "Person" object to the "DoWork()" method so lets quickly create a Person object with properties for a Name, Age and the types of Shoes they own (first thing that popped into my head). This class will also serve as the structure for our JSON object.

[code:c#]
[Serializable]
[DataContract( Namespace = "http://www.dennydotnet.com/", Name = "Person" )]
public class Person
{
 private string _name = string.Empty;
 private int _age = 0;

 [DataMember( IsRequired = true, Name = "Name" )]
 public string Name
 {
  get { return _name; }
  set { _name = value; }
 }

 [DataMember( IsRequired = true, Name = "Age" )]
 public int Age
 {
  get { return _age; }
  set { _age = value; }
 }

 [DataMember( IsRequired = true, Name = "Shoes" )]
 public List<String> Shoes;

}
[/code]

We've decorated our Person class as a DataContract specifying the Namespace and Name. We've also decorated our properties with a DataMember attribute. We've set "IsRequired" for each one to true and specified the Name. You really only need to specify the "Name" if it's going to be different than the property name. For example you could have a property named "Level" and the DataMember attribute's Name set to "Rank." We can now go back and modify our "DoWork()" method to receive a Person object as a param. It should now look like the following:

[code:c#]
[OperationContract]
[WebGet( RequestFormat=WebMessageFormat.Json )]
public void DoWork(Person p)
{
 // Add your operation implementation here
 return;
}
[/code]

The Web.Config File:

You'll need to make a few changes to your web.config file before you can access your service. You'll need to add a serviceBehavior to allow httpGet and we'll also add some helpful debugging options too. Add the following to your web.config:

Below </endpointBehaviors>

[code:xml]
<serviceBehaviors>
 <behavior name="ServiceAspNetAjaxBehavior">
  <serviceMetadata httpGetEnabled="true" httpGetUrl="" />
  <serviceDebug httpHelpPageEnabled="true" includeExceptionDetailInFaults="true" />
 </behavior>
</serviceBehaviors>
[/code]


Between <services>[here]</services> your service node should look like this:
[code:xml]
<service name="Service" behaviorConfiguration="ServiceAspNetAjaxBehavior">
 <endpoint address="" behaviorConfiguration="ServiceAspNetAjaxBehavior"
  binding="webHttpBinding" contract="Service" />
 <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
[/code]

A security note about the following line:

[code:xml]
<serviceDebug httpHelpPageEnabled="true" includeExceptionDetailInFaults="true" />
[/code]


Allowing exception details can expose internal application information including personally identifiable or otherwise sensitive information. Setting the option to true is only recommended as a way to temporarily debug your service!!

Your Web.Config should look like the following: (pardon the colors)

The Front-End:

Now that the service is created and configured we can move to the front-end (make sure jQuery.js is included in your ASP.NET page). First let's create a sample JSON object that we will pass to the service. We'll create the JSON object based on the structure of the Person class.

[code:js]
var mydata = { "Name":"Denny", "Age":23, "Shoes":["Nike","Osiris","Etnies"] };
[/code]


If you're not too familiar with JSON this is what our JSON object looks like as an object (JsonViewer):

We need to somehow communicate with the WCF service and since we're using jQuery we can use the library's built-in AJAX methods. The code below creates an AJAX call. the headers are set to GET and the contentType is application/json. We set the url to the path to our WCF service's svc file with a trailing / and then the name of the method we want to execute. In this case we're calling the "DoWork()" method. "data" will be passed in to our function and processData should be set to false so that jquery does not try to auto-process our data. We've also added a success and error function to let us know what happens after executing the AJAX.

[code:js]
function sendAJAX(data) {
 $.ajax({
  type: "GET",
  contentType: "application/json",
  url: "Service.svc/DoWork",
  data: data,
  processData: false,
  success:
   function(msg){
     alert( "Data Saved!" );
   },
  error:
   function(XMLHttpRequest, textStatus, errorThrown){
       alert( "Error Occured!" );
   }
 });
}
[/code]

Now unfortunately there is a small issue here. We must send the actual JSON string as the value for DoWork's Person p param and there's no easy way of turning your JSON object into a string. If you try "data.toString()" you'll just get an "[object Object]" value (remind you of anything?), which is not what we want. So here's a slightly modified function that will take your JSON and turn it into a string.

Note* The JSON de/serialization handles Date/Time in a specific way. The json2string function below does not take this into account. I'm sure there are some implementations out there which will work with ASP.NET AJAX but this one does not. For more information on this you can go here.

Update [4/11/08]: The javascript below has a few issues so it's been suggested that you should use the JSON.org version to "stringify" your object. You can download the script from here.

Update [4/25/08]: Rick Strahl has modified the JSON.org script so that it will properly create the dates to work with ASP.NET AJAX (read his post)

[code:js]
function json2string(strObject) {
 var c, i, l, s = '', v, p;

 switch (typeof strObject) {
 case 'object':
  if (strObject) {
   if (strObject.length && typeof strObject.length == 'number') {
    for (i = 0; i < strObject.length; ++i) {
     v = json2string(strObject[i]);
     if (s) {
      s += ',';
     }
     s += v;
    }
    return '[' + s + ']';
   } else if (typeof strObject.toString != 'undefined') {
    for (i in strObject) {
     v = strObject[i];
     if (typeof v != 'undefined' && typeof v != 'function') {
      v = json2string(v);
      if (s) {
       s += ',';
      }
      s += json2string(i) + ':' + v;
     }
    }
    return '{' + s + '}';
   }
  }
  return 'null';
 case 'number':
  return isFinite(strObject) ? String(strObject) : 'null';
 case 'string':
  l = strObject.length;
  s = '"';
  for (i = 0; i < l; i += 1) {
   c = strObject.charAt(i);
   if (c >= ' ') {
    if (c == '\\' || c == '"') {
     s += '\\';
    }
    s += c;
   } else {
    switch (c) {
     case '\b':
      s += '\\b';
      break;
     case '\f':
      s += '\\f';
      break;
     case '\n':
      s += '\\n';
      break;
     case '\r':
      s += '\\r';
      break;
     case '\t':
      s += '\\t';
      break;
     default:
      c = c.charCodeAt();
      s += '\\u00' + Math.floor(c / 16).toString(16) +
       (c % 16).toString(16);
    }
   }
  }
  return s + '"';
 case 'boolean':
  return String(strObject);
 default:
  return 'null';
 }
}
[/code]

Now that we have a function to turn our JSON object into a string we need to go back and update the "mydata" variable that we defined above. After applying the json2string function we should have the following: 

[code:js]
var mydata = { "Name":"Denny", "Age":23, "Shoes":["Nike","Osiris","Etnies"] };
var jsonStr = "p=" + json2string(mydata);
[/code]

Notice that I prepended the "p=" string to our json string. "p" matches the parameter name in our "DoWork()" method. So if our parameter name was "Dude" ( i.e. DoWork(Person Dude) ) then we would use "Dude=" instead.

Now that we've built the querystring to the web service we can see what our call is going to look like:

http://www.dennydotnet.com/Service.svc/DoWork/?p={ "Name":"Denny", "Age":23, "Shoes":["Nike","Osiris","Etnies"] }

You may get a URL Encoded value too, which would look like:

http://www.dennydotnet.com/Service.svc/DoWork/?p=%7b+%22Name%22%3a%22Denny%22%2c+%22Age%22%3a23%2c+%22Shoes%22%3a%5b%22Nike%22%2c%22Osiris%22%2c%22Etnies%22%5d+%7d%3b

Go ahead and link "jsonStr" to the "SendAjax()" javascript method so we can debug our service and verify that the data was passed through to the service... check it out:

And now you just need to implement your logic in the DoWork() method. Notice how you don't have to do any de/serialization on the WCF service side either, it's already done for you. Now you should certainly implement some exception management so that you don't get any invalid data, or even add some authentication, but I'll leave that up to you...

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Currently rated 5.0 by 2 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , , ,
Posted by Denny on Monday, March 03, 2008 2:40 PM
Permalink | Comments (5) | Post RSSRSS comment feed

Eloquent JavaScript - JavaScript Tutorials

Marijn Haverbeke has put together an e-book named Eloquent JavaScript that not only has great content, but also comes with an integrated interface for editing and running the examples directly from the "pages."

I had to post this since the site is such an excellent resource for JavaScript. Running the examples is incredibly intuitive and easy. Excellent work on Mr. Haverbeke's part!

The post/link originated on Ajaxian: http://ajaxian.com/archives/eloquent-javascript 

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: Client-Side | General
Posted by Denny on Tuesday, January 22, 2008 9:44 AM
Permalink | Comments (0) | Post RSSRSS comment feed

ScreenCast: MVC, jQuery and REST

So I recently picked up a copy of Camtasia Studio (www.techsmith.com) and wanted to give it a shot by creating my first screen cast.

This screen cast is going to show you how to create an MVC application that uses jQuery (http://www.jquery.com/) to do some AJAX calls against a REST url. You should be familiar with jQuery and the MVC framework but I tried to keep it as simple as possible. The screen cast runs for about 25 minutes - Click the image below to start watching.

Comments, questions and suggestions are welcome...

You can download the sample project here: MVCjQueryREST.zip (41.41 kb)

kick it on DotNetKicks.com

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Currently rated 4.8 by 6 people

  • Currently 4.833333/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,
Posted by Denny on Sunday, December 16, 2007 8:41 PM
Permalink | Comments (9) | Post RSSRSS comment feed

Animating ASP.NET AJAX Update Panel Updates

Do you dislike the way that ASP.NET AJAX Update Panels update (or replace the content within the update panel)? Is it not flashy and Web 2.0 enough for you? Well fear no more! I've devised a straight-forward script to help you animate your update panel updates. This script uses jQuery (www.jquery.com) to animate the content when an update panel updates. It can easily be modified to use another library such as Scriptaculous. It uses javaScript to override ASP.NET AJAX's _updatePanel method within the PageRequestManager (the method which does the actual replacing of the content).

I've commented the script so you can understand what it's doing:

[code:js]
$(document).ready(
  function() {
      // SAVE the original _updatePanel function for later use.
      var old_prm_updatePanel = Sys.WebForms.PageRequestManager.getInstance()._updatePanel; 

      // Overwrite the original method with our code which will apply animation.
      // (Note: The method signature remains the same)
      Sys.WebForms.PageRequestManager.getInstance()._updatePanel = 
          function(updatePanelElement, rendering) {
              // Using jQuery to hide (animate) the element. Then use the callback function 
              // to load and show the new data. You don't want to update the
              // data beforehand otherwise you'll see your update panel flicker.
              $(updatePanelElement).hide('slow',
                  function() {
                      // Pass the old function and the args
                      loadShowUpdatePanel(old_prm_updatePanel, updatePanelElement, rendering);
                  });
          }
   });
 
function loadShowUpdatePanel(old_prm_updatePanel, updatePanelElement, rendering) {
    // Call the original (old) function with context of Page Request Manager instance.
    // We call the original method so ASP.NET AJAX can do all the necessary actions.
    old_prm_updatePanel.apply(Sys.WebForms.PageRequestManager.getInstance(),
                                                               new Array(updatePanelElement, rendering));

    // using jQuery again to show (animate) the update panel.
    $(updatePanelElement).show('slow');
}
[/code]

And that's all you need. This script isn't just limited to animating the update panel update either... You can extend this script to do anything you want immediately before and after the new content is displayed. The main difference between this method and using the add_BeginRequest or add_EndRequest methods is the timing. This script will fire exactly before and after the update takes place - This would not be a good place to show a loading screen because the AJAX call has already been made, there's nothing to wait for. Whereas the BeginRequest executes before the AJAX call and EndRequest fires after the update has completed - This would be good to apply a loading screen.

kick it on DotNetKicks.com

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Currently rated 5.0 by 2 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by Denny on Thursday, November 08, 2007 11:08 PM
Permalink | Comments (3) | Post RSSRSS comment feed

A DataTable Serializer for ASP.NET AJAX

A DataTable Serializer for ASP.NET AJAX, implements JavaScriptConverter. Note that I did not implement a Deserialize method since I am using this for read only data.

[code:c#]
/// <summary>
/// DataTable to JSON converter
/// </summary>
public class JavaScriptDataTableConverter : JavaScriptConverter {
 public override object Deserialize( IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer ) {
  throw new NotImplementedException( "Deserialize is not implemented." );
 }

 public override IDictionary<string, object> Serialize( object obj, JavaScriptSerializer serializer ) {
  DataTable dt = obj as DataTable;
  Dictionary<string, object> result = new Dictionary<string, object>();

  if( dt != null && dt.Rows.Count > 0 ) {
   // List for row values
   List<object> rowValues = new List<object>();

   foreach( DataRow dr in dt.Rows ) {
    // Dictionary for col name / col value
    Dictionary<string, object> colValues = new Dictionary<string, object>();

    foreach( DataColumn dc in dt.Columns ) {
     colValues.Add( dc.ColumnName, // col name
      ( string.Empty == dr[dc].ToString() ) ? null : dr[dc] ); // col value
    }

    // Add values to row
    rowValues.Add( colValues );
   }

   // Add rows to serialized object
   result["rows"] = rowValues;
  }

  return result;
 }

 public override IEnumerable<Type> SupportedTypes {
  //Define the DataTable as a supported type.
  get {
   return new System.Collections.ObjectModel.ReadOnlyCollection<Type>(
    new List<Type>(
     new Type[] { typeof( DataTable ) }
    )
   );
  }
 }
}
[/code]

And how do you implement this? In a web service...

[code:c#]
using System.Web.Script.Serialization;

// ...

[WebMethod()]
[ScriptMethod( ResponseFormat = ResponseFormat.Json )]
public string TestJS( int Id ) {
 JavaScriptSerializer toJSON = new JavaScriptSerializer();
 toJSON.RegisterConverters( new JavaScriptConverter[] { new JavaScriptDataTableConverter() } );

 DataTable dt = new Query( Log.Schema )
   .WHERE( Log.Columns.ID, Id )
   .ExecuteDataSet().Tables[0];

 return toJSON.Serialize( dt );
}
[/code]

That's all there is to it! Just deserialize to an object on the client-side and you're good to go!

Side Note: There is a DataTable serializer from Microsoft in the ASP.NET Futures package.

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Currently rated 4.5 by 2 people

  • Currently 4.5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,
Posted by Denny on Friday, September 14, 2007 4:05 PM
Permalink | Comments (2) | Post RSSRSS comment feed

UpdatePanels: When and Where

I've been using the ASP.NET AJAX Update Panels for quite some time now and have picked up a lot of tips on when and how to use them. Update Panels were intended to allow the developer to do Partial Page Updates. Usually what you see is Update Panels updating nearly the entire page which completely defeats the purpose of Update Panels!

Here are some good tips to take into account when developing with Update Panels:

#1. One thing I notice is that people want to stuff all their functionality into one page with multiple hidden/visible panels. Then utilize the functionality by showing/hiding the panels based on actions within the page. This can lead to very confusing code...

If you're changing from one action which does a lot of functionality with X to an action which does a lot of functionality with Y then separate the functionality and use a page postback to switch between those pages. Don't throw everything together into one update panel and separate it by hidden panels. You'll end up with a ton of code which is not resuable and difficult to understand. Separate your functionality just like you would separate your DAL, BL and Presentation.

Example for an Admin section:
  • User Management (insert, update, delete users)
  • Settings (change your web app's settings)
  • Media Management (insert, update, delete media)
  • etc...

#2. Separate your Update Panels. Instead of throwing everything into one update panel break it up! Plan what areas of your page will need to update and what will trigger them to update. This will save you an insane amount of bandwidth (and download time) and return much better performance.

Example:
Lets say you have 3 areas on your page that will allow a user to: select a category, select a video and then watch the video.

  • Part 1 displays a list of categories
  • Part 2 displays a list of videos within that category
  • Part 3 displays a video player

Lets think logically about the flow of execution with the 3 parts. First a user picks a category in Part 1. Then they select which video they want to watch in Part 2. And finally the video displays in Part 3 and begins playing.

So there are 2 steps involved to watch a video:

  1. Pick a category
  2. Pick a video


And 2 triggers:

  1. "Click" a category
  2. "Click" a video



(Each arrow represents a click)

So we've got the basic idea down now how do we determine WHERE we need update panels? We need to determine what parts change. The only parts that change are Part 2 which shows a list of videos within the selected category and Part 3 which plays the selected video. Part 1 will not change because nothing within that part changes. Part 1 is only used to select a category and the categories are loaded at Page_Load.

(Of course if you added paging or sorting to Part 1 you could then use an update panel but for this example Categories are static.)

So you have 2 parts that change meaning you only need 2 update panels, one for Part 2 and one for Part 3. Now how do we trigger these updates? Based on the flow we determined above we know what triggers are needed...

Triggers:

  • Part 2 needs to update when a category is selected from Part 1.
  • Part 3 should update when a video is selected from Part 2.

We also want to hide the video player when the user selects a new category because it wouldn't make sense to continue showing a video from the "Comedy" category after they selected the "Drama" category. So we'll need one more trigger:

  • Part 3 should update when a category has been selected since we don't want to display the old video when they select a new category.


(Each arrow represents where the item is triggered from [start of line inside part] and what part it affects [end of line])

And that's all we need to properly separate our update panels. The cool thing about upate panels is that your trigger control does not need to be within the same update panel. In other words, it can be located anywhere on your page outside the update panel. That's why we only need 2 update panels. The triggers in part 1 can be set programatically or through the update panel "triggers" GUI from the properties menu.

Quick Tip: If you want to know how to set a trigger programatically then read this post.

What's the benefit of separating the update panels? Alot of Bandwidth! Update panels respond with their entire rendered contents when doing an AJAX call. Update panels also attach any control viewstates to the response. If you were to place the entire content of the example above in one update panel you'll be uploading and downloading everything every time you do a callback. On the other hand if you separate your update panels, like the example above, you'll only download the contents of the update panel that has been triggered.

Quick Tip: If a control within an update panel does not need viewstate enabled then disable it! This is a good way to decrease the size of the response.

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by SuperGhost on Thursday, August 30, 2007 2:19 PM
Permalink | Comments (1) | Post RSSRSS comment feed

TypeWatch: jQuery Plugin

Earlier this week I created a jQuery plug-in that allows you to potentially determine when a user has finished typing in a textbox. I created it for a search textbox on one of my websites so that I could return results by firing some AJAX after they're done typing. It could help with an AJAX auto-complete implementation too.

[UPDATED 11/02/07]

There are 4 settings you can set:

1. callback: The function to callback after the user has "finished" typing. Default void.
2. wait: The number of milliseconds to wait before the plugin considers that typing has finished. Default 750.
3. highlight: Aesthetics, determines if the text should be highlighted when the textbox receives focus. Default true.
4. enterkey: Determines if the ENTER key will fire the callback rather than wait for the timeout. Default true.

How it works:

For each textbox or textarea matched through jQuery it creates a timer which gets reset upon every [KeyDown] event. If the timer's [wait] is reached then the user has finished typing, or stopped typing long enough for the timer to reach its [wait] interval.

The callback will not execute if the length of text is less than 3 characters. Also, if the timer's [wait] interval is reached and the text has not changed it will not execute the callback. So if you change "some text" to "SOME TEXT" the callback will not execute. However if you have set the option enterkey to true, or left it at default, the callback will be executed when the ENTER key is pressed.

You can get the debug and packed version at: http://jquery.com/plugins/project/TypeWatch

The latest version 1.1.0 fixes an issue that any key would cause the callback to execute - including Home/End/Page Up etc... Now it will only fire if the text has changed.

DEMO:

Click here for the Live Demo

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Currently rated 3.7 by 29 people

  • Currently 3.689655/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: Client-Side
Posted by Denny on Friday, August 17, 2007 10:23 AM
Permalink | Comments (25) | Post RSSRSS comment feed

JavaScript Model Objects (JMO) - An Idea

A rough prototype of what I like to call "JavaScript Model Objects" or JMO for short.While playing with ASP.NET AJAX I came across an idea of using AJAX, JSON, and JavaScript to bind data onto page elements. So today I decided to play around and try to create a "repeater" but on the client-side. This is the gist of the idea...

#1. Get the data which I want to bind using AJAX and JSON.

Example JSON data: 

var myTestObj =
{
            "rows":
                        [{"id":1, "title":"Test one", "imagesrc":"images/ajax.gif", "isTest":true},
                        {"id":2, "title":"Test two", "imagesrc":"images/playmini.gif", "isTest":true},
                        {"id":3, "title":"Test three", "imagesrc":"images/playmini.gif", "isTest":true}]
}

In this example the JSON data must have "rows" with an array of the row columns/values.

#2. Define the template that I want to bind to. This is defined directly on my HTML page.

Example:

<table>
            <tr id="JMO1">
                        <td style="border: solid 1px black">!id!</td>
                        <td style="border: solid 1px black">!title!</td>
                        <td style="border: solid 1px black"><img src="!imagesrc!" /></td>
                        <td style="border: solid 1px black">!isTest!</td>
            </tr>
</table>

As you can see I have a table with 4 columns. I want to bind to the TR object so I give my TR an id. The places where I want the data to appear are surrounded by exclamation points, like !<name>!. Also notice that I have given the TR tag an ID of "JMO1" which I will use to pass to my binding function. The TR tag is essentially my "Model Object."

#3. The functions to bind the data to my model object... Please note this is a very rough sketch of the functionality, and yes I am using jQuery:

function initJMO(modelObj, dataObj) {    
        var obj = $(modelObj);
        var data = eval(dataObj);
        var dataMembers = getDataMembers(obj)
                  
        if (dataMembers.length > 0) {
                    // Deep clone the model, save reference
                    //var clone = obj.clone(true);
                    var dataClone = obj[0].outerHTML;
                    
                    for (x = data.rows.length-1; x >= 0; x--) {
                          var thisRow = dataClone;
                                   
                          for (i = 0; i < dataMembers.length; i++) {
                                  var rg = new RegExp("!" + dataMembers[i] + "!"); rg.global = true;

                                  if (dataMembers[i] == "length") {
                                         ev = data.rows.length.toString();
                                  } else {
                                         ev = eval("data.rows[" + x + "]." + dataMembers[i]).toString();
                                  }
                                        
                                  thisRow = thisRow.replace(rg, ev);
                          }

                          obj.after(thisRow);
                    }
                            
                    // Remove model
                    obj.remove();
        }
}

function getDataMembers(obj) {
              var str = obj[0].outerHTML;

              if (str.length > 0) {
                          var rg = /!(\w+)!/g;
                          var match = str.match(rg);
                          var dMembers = [];
                          dMembers.push("length");

                          if (match != null) {
                                      for(i = 0; i < match.length; i++) {
                                            dMembers.push(match[i].replace(/!/g,""));
                                      }
                          }

                          return dMembers;
              } else {
                          return [];
              }
}

$(function() {
              initJMO("#JMO1", myTestObj);
} );

initJMO requires 2 params... 1 is the model object (our TR in this case). 2 is the data object (our un-eval'd JSON). 

initJMO clones the model object, finds all the data members (column names) we want to bind to and then goes through and replaces each !<name>! with the corresponding JSON column's data. It then appends the source of our cloned/replaced element after the model object, thus repeating the data with each row of our data object. Finally initJMO removes the model object from the page.

So what you get is your model object repeated with every row of your data object.

The cool thing about this is you can define ANY element as the model object!Now yes this still needs a lot of work and there are a few issues with it but I'd like to get some feedback. Good idea? Has this been done before?

A sample page can be viewed here: http://www.dennydotnet.com/Test/Default2.aspx

Digg It!