Home > AJAX, ASP.NET, WCF, c#, jQuery > WCF Services, AJAX, and the new ‘dynamic’ keyword…

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);
}
Categories: AJAX, ASP.NET, WCF, c#, jQuery Tags:
  1. November 14th, 2011 at 04:37 | #1

    Doesn’t serializer.Serialize() return a serialized string, but WebInvoke also automatically serializes the return, so you end up with double-serialized/escaped json?

  1. No trackbacks yet.