Using C# objects inside of your Javascript

Here’s an easy way to get your C# objects transferred via AJAX & JSON so that you can use them inside of your html pages Javascript. First here’s the C# WebMethod we want to call…

[WebMethod]
public static string Test() {
  var data = new {
   page = 1,
   totalRows = 2,
   rows = new List() {
     new DummyData { firstname = "Ross", lastname = "Cooper" },
     new DummyData { firstname = "Bob", lastname = "Sagat" }
   }
  };
  return new JavaScriptSerializer().Serialize(data);
}

And here is the javascript that uses jQuery to call Test() via AJAX and decode the returned JSON into a javascript object…

$(document).ready(function() {
  $.ajax({
    type: "POST",
    url: "Default.aspx/Test",
    data: "{}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
     var data = eval("(" + msg.d + ")");
     alert(data.rows[0].firstname); // prints "Ross"
    }
  });
});