A technical blog about programming and technology.

Saturday, August 4, 2007

Anonymous types and Page Methods

I've been playing with asp.net Ajax for the last couple of days in VS Orcas beta 1(haven't downloaded Beta 2 as yet), and I wondered if it was possible to return an anonymous type to JavaScript using the PageMethods feature. This is a very useful for web scenarios, for example you may want to return a list of tuples and bind a list of key and value pairs to a drop down list. Surprisingly it just works.


public class Person {
public string Name { get; set; }
public int Age { get; set; }
public int Id { get; set; }

public static List GetPersons() {
return new List { new Person { Name = "David", Age = 20, Id=1 }, new Person { Name = "John", Age = 10,Id=2 },
new Person { Name = "Harry", Age = 30,Id=3 }, new Person { Name = "Peter", Age = 40,Id=4 }, new Person { Name = "Jodi", Age = 15,Id=5 }};

public static object GetData() {
return from p in GetPersons()
where p.Age >= 20
select new { p.Id, p.Name };

On the server side the static method that is exposed to JavaScript is marked with the WebMethod attribute. The return type of the method is object since we can't name the return type. The result of the query expression is an IEnumerable< class { int Id; string Name }>, on the JavaScript side we get a collection of these nameless types that we can iterate over and populate a drop down list. Try it out, I thought it was very cool they way we could leverage new C# 3 features to enhance other programming domains.


<script type="text/javascript">
function populate() {
PageMethods.GetData(function(res) {
var list = $get('list');
var options = "";
for(var idx in res) {
options += "<option value='" + res[idx].Id + "'>" + res[idx].Name + "</option>";
list.innerHTML = "<select onchange='showValue(this)'>" + options + "</select>";

function showValue(list) {
alert("Id = " + list.options[list.selectedIndex].value);
<form id="form1" runat="server">
<asp:ScriptManager EnablePageMethods="true" runat="server">
<a href="javascript:populate()">Populate Drop Down</a> <br />
<div id="list" />

Technorati tags: , , ,

No comments: