Calling a WCF Service from jQuery

For this example I build a simple WCF service that registers your mood for today in a MoodLog; called Moodr. There are five different mood states, with corresponding emoticons in the database. I use the Entity Framework for my Moodr model.

Each entity gets his own Repository class and a corresponding Data Transfer Object (DTO) class. DTOs are used as return types between the webservice and the AJAX client.

using System;
using System.Collections.Generic;
using System.Linq;

namespace Moodr.Repositories
{
    public class MoodLogRepository
    {
        public static void UpsertMoodLog(MoodLog moodLog)
        {
            var context = new MoodrEntities();
            var today = DateTime.Now.Date;
            var query = from l in context.MoodLogs
                        where l.Date == today select l;

            if (query.Any())
            {
                var existingMoodLog = query.First();
                existingMoodLog.MoodId = moodLog.MoodId;
            }
            else
            {
                context.MoodLogs.AddObject(moodLog);
            }

            context.SaveChanges();
        }

        public static IEnumerable<DtoMoodLog> GetAll()
        {
            var context = new MoodrEntities();
            var query = from l in context.MoodLogs
                        orderby l.Date descending
                        select new DtoMoodLog
                        {
                            Date = l.Date,
                            Emoticon = new DtoEmoticon
                            {
                                Symbol = l.Mood.Emoticon.Symbol,
                            }
                        };

            return query.ToList();
        }
    }

    public class DtoMoodLog
    {
        public DateTime Date { get; set; }
        public DtoEmoticon Emoticon { get; set; }
    }
}

The Moodr WCF service has two methods for retrieving Mood (GetMoods) and MoodLog (GetMoodLogs) data, and one to store the mood of the day (WriteMoodLog) accepting a moodId parameter.

using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using Moodr.Repositories;

namespace Moodr
{
    [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode =
        AspNetCompatibilityRequirementsMode.Allowed)]
    public class MoodrService
    {
        [OperationContract]
        [WebGet(RequestFormat = WebMessageFormat.Json)]
        public IEnumerable<DtoMood> GetMoods()
        {
            var result = MoodRepository.GetAll();

            return result;
        }

        [OperationContract]
        [WebGet(RequestFormat = WebMessageFormat.Json)]
        public void WriteMoodLog(int moodId)
        {
            try
            {
                MoodLog moodLog = new MoodLog
                {
                    MoodId = moodId,
                    Date = DateTime.Now
                };

                MoodLogRepository.UpsertMoodLog(moodLog);
            }
            catch (Exception)
            {
                WebOperationContext.Current.OutgoingResponse.StatusCode =
                    System.Net.HttpStatusCode.NotAcceptable;
            }
        }

        [OperationContract]
        [WebGet(RequestFormat = WebMessageFormat.Json)]
        public IEnumerable<DtoMoodLog> GetMoodLogs()
        {
            var result = MoodLogRepository.GetAll();

            return result;
        }
    }
}

Finally some jQuery magic behind the scene to wire it all up.

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="Moodr._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
    <script src="Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $.ajax({
                type: "GET",
                url: '/MoodrService.svc/GetMoods',
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                success: function (moodList) {
                    var moodPicker = $('div#MoodPicker');
                    $(moodList.d).each(function () {
                        moodPicker.html(moodPicker.html() +
                            "<input type='radio' name='moodradio' id='moodradio'" +
                                this.ID + " value=" + this.ID + " />" +
                            "<label for='moodradio'" + this.ID + ">" +
                                this.Name + "</label><br/>"
                        );
                    });
                },
                error: onError
            });

            $('#enterButton').click(function () {
                var checkedMood = $('input[name=moodradio]:checked');
                $.ajax({
                    type: "GET",
                    url: '/MoodrService.svc/WriteMoodLog',
                    data: { 'moodId': checkedMood.val() },
                    dataType: 'json',
                    contentType: "application/json; charset=utf-8",
                    success: function (moodLogList) {
                        var MoodLogs = $('div#MoodLogs');
                        MoodLogs.html('Your mood the last ' + $(moodLogList.d).length + ' days<br/><table>');
                        $(moodLogList.d).each(function () {
                            MoodLogs.append(
                            "<tr><td>" + this.Emoticon.Symbol +
                            "</td></tr/>");
                        });
                        MoodLogs.append('</table>');
                        $('#resultDiv').html('So you feel ' + checkedMood.next().text());
                    },
                    error: onError
                });
            });
        });

        function onError(error) {
            alert("Error: " + error.status);
        }
    </script>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <div id="MoodPicker">
    </div>
    <br />
    <div>
        <input id='enterButton' type='button' value='Enter mood' />
        <span id="resultDiv"></span>
    </div>
    <hr />
    <div id="MoodLogs"></div>
</asp:Content>


 

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>