May 17, 2010

Creating JSON using ASP Repeater

I had to implement an interesting task over the last few days. A part of the task, had to deal with what this article is all about. It sounded simple and easy but it turned ugly! The aim was to use ASP.Net's Repeater tag to create JSON when the page is loaded and later use it for some user manipulations and ajax operation. But in this article, we will see how to create JSON.

The ASP Repeater is a very handy tag. Everybody know it, but at times you will have to get messy with it. You get to solve many interesting problems with it. I my real case I had to deal with multiple repeater tags. Here we will have a look at one simple example. Its assume we want to make a JSON with product information. Lets just implement it:

<asp:Repeater ID="ProductJSON" runat="server">
 <HeaderTemplate>
  <script type="text/javascript">
  var products = [
 </HeaderTemplate>
 <ItemTemplate>{ pid: '<%#((Product)Container.DataItem).ProductID%>',
  name: '<%#((Product)Container.DataItem).ProductName%>', 
  image: '<%#((Product)Container.DataItem).Image %>',                        
  summary: '<%#((Product)Container.DataItem).Summary %>',
  price: '<%#((Ecomm.Code.ProductDM)Container.DataItem).Price%>'},
 </ItemTemplate>    
 <FooterTemplate>
  ];</script>
 </FooterTemplate>
</asp:Repeater>
That was it! really? well unfortunately No! Problems occur when your javascipt start using this JSON. You will notice that the last JSON object completes with a comma (which is a syntax error). The hard part for me started from here. How do I eliminate the final comma so that the JSON array is correctly represented. Finally after lot of googling and trails, I got the correct result. Here is the final code:
<asp:Repeater ID="ProductJSON" runat="server">
 <HeaderTemplate>
  <script type="text/javascript">
  var products = [
 </HeaderTemplate>
 <ItemTemplate>{ pid: '<%#((Product)Container.DataItem).ProductID%>',
  name: '<%#((Product)Container.DataItem).ProductName%>', 
  image: '<%#((Product)Container.DataItem).Image %>',                        
  summary: '<%#((Product)Container.DataItem).Summary %>',
  price: '<%#((Ecomm.Code.ProductDM)Container.DataItem).Price%>'}
  <%#Container.ItemIndex==(((List<Product>)ListViewDisplay.DataSource).Count - 1)?' ':','%>
 </ItemTemplate>    
 <FooterTemplate>
  ];</script>
 </FooterTemplate>
</asp:Repeater>
Many of you will now argue why not use some event like PreRender or some other events.. I would say for doing such a thing, when you need to have other complex solutions! I hope this will come helpful to others.

1 comment :

Simon said...

You could use:
,