WCF Services, AJAX, and the new ‘dynamic’ keyword

Recently I had a project where I wanted to return multiple sets of data via AJAX with a single call, although the sets of data were different types (from different tables altogether). Anything to save some bandwidth/roundtrips, right? I made an attempt at using the new dynamic type to create my service method and to hold my sets of data, and was able to use the JavaScriptSerializer to return the JSON that I needed for my jQuery web service. Example below 🙂

[WebInvoke(Method = POST,
BodyStyle = WebMessageBodyStyle.WrappedRequest,
ResponseFormat = WebMessageFormat.Json)]
public dynamic getPriceRelatedData()
{
    EasyGalleryDataContext data = new EasyGalleryDataContext();

    var sizes = from szs in data.Sizes
        select new {
            szs.SizeID,
            szs.Height,
            szs.Width
        };

    var finishes = from fn in data.Finishes
        select new
        {
            fn.FinishID,
            fn.Title
        };

    dynamic pricesheets = from ps in data.PriceSheets
                        select new
                        {
                            ps.PriceSheetID,
                            ps.Title,
                            PriceSheetItems = (from psi in data.PriceSheetItems
                                                where psi.PriceSheetID == ps.PriceSheetID
                                                select new
                                                {
                                                    psi.PriceSheetItemID,
                                                    psi.PriceSheetID,
                                                    psi.SizeID,
                                                    psi.FinishID,
                                                    psi.Price
                                                })
                        };

    dynamic[] results = { sizes, finishes, pricesheets };

    JavaScriptSerializer serializer = new JavaScriptSerializer();
    return serializer.Serialize(results);
}

Leave a Reply

Your email address will not be published. Required fields are marked *