Tuesday, June 28, 2011

Populating a Telerik RadListBox with JSON on the Client Side

Ok, this is the poor man's way to do this. I'm actually not calling a web service to pull my jSON string back from the server, but rather a RadScriptManager, but this will get you going.

My approach. Note it assumed that you have a Telerik RadAjaxScriptManager on your page (or master page that you will need to access).

Step 1 Include the Following Namespace in Page Code Behind Class

using System.Web.Script.Serialization;

Step 2 Create a Class Object to be Serialized in the Page Code Behind Class

public class itm
   public string val { get; set; }
   public string txt { get; set; }

Step 3 Create a Serialization Method in the Page Code Behind Class

public string ToJSON ( object obj )
  JavaScriptSerializer serializer = new JavaScriptSerializer ();
  return serializer.Serialize ( obj );

Step 4 Create a Method in the Page Code Behind Class That Will Take Data, Populate a list of itms,Serialize that list into a jSON string, then call the RadAjaxManager's ResponseScripts.Add method to pass the jSON string to the client side.

A few notes here. One you could use AJAX to make a call to a web service to accomplish the same thing, for my example was just doing a basic test so I didn't bother. Also note that you will need to call this method somewhere (on a databind of a form view, Page_Load, whatever, inorder for the method to do anything). Note I'm doing a very lazy and inefficient way to get my data out of the database, I actually defined a sql datasource on my aspx page, and then reference it in the code behind. You probably will want to get your data another way...

void JSONListBoxItems ( hsRadListBox lst, SqlDataSource ds, string txt, string val )
  lst.Items.Clear ();
  List<itm> itms = new List<itm> ();
  if ( lst == null || ds == null || string.IsNullOrEmpty ( txt ) || string.IsNullOrEmpty ( val ) )
    DataView view = (DataView)ds.Select ( DataSourceSelectArguments.Empty );
    if ( view != null && view.ToTable () != null )
      DataTable table = view.ToTable ();
      for ( int i = 0 ; i< table.Rows.Count ; i++ )
       itm t = new itm ();
       t.txt = table.Rows[ i ][ txt ].ToString ();
       t.val = table.Rows[ i ][ val ].ToString ();
       itms.Add ( t );
   myRadAjaxManager.ResponseScripts.Add ("POPRadListBX('" + lst.ClientID.ToString () + "'," + ToJSON ( itms ) + ");" );

Step 5, Add the Following Javascript on the ASPX page.

function POPRadListBX(tid, js) {
        var lst = $find(tid);
        if (lst != null) {
          var zzz = lst.get_items();
          for (var i = 0; i < js.length; i++) {
            var item = new Telerik.Web.UI.RadListBoxItem();

Done. If I have time I'll circle back and make a downloadable example.