Tuesday, July 23, 2013

Call a WCF web service using jQuery

First, add an AJAX-enabled WCF Service to your project.  There is a Visual Studio template for this.  Add a web method like the following:

    <OperationContract(), WebGet()>
    Public Function GetFood(inputId As String) As Food()
        Dim ReturnFood As New List(Of Food)
        If inputId = 1 Then
            ReturnFood.Add(New Food With {.Id = "1", .Name = "Bananas", .Color = "Yellow"})
        ElseIf inputId = 2 Then
            ReturnFood.Add(New Food With {.Id = "2", .Name = "Apples", .Color = "Red"})
        Else
            ReturnFood.Add(New Food With {.Id = "1", .Name = "Bananas", .Color = "Yellow"})
            ReturnFood.Add(New Food With {.Id = "2", .Name = "Apples", .Color = "Red"})
        End If
        Return ReturnFood.ToArray
    End Function

Notice the WebGet attribute.  This allows your web method to be called using a GET operation.  Very important.  Won't work without this.  What this means is if you browse to http://yourserver/AjaxGetResultsService.svc/GetFood, you will get Json back in return.

Also notice that I'm returning an array of Food which is a class I made up.  The .net framework will automatically turn this into Json for you.

So, if you had a button with an id of buttonPopulateFood, the following jQuery code would call this method and display the results.

    $("#buttonPopulateFood").click(function () {
        $.ajax({
            url: "AjaxGetResultsService.svc/GetFood",
            type: "GET",
            dataType: "json",
            data: {
                inputId: "1"
            },
            success: function (json) {
                displayJson(json);
            },
            error: function () { alert("You have failed.") }
        });
    });

Here is the displayJson function I'm calling.  I'm using the each function to iterate through the json array.

function displayJson(jsonData) {
    $.each(jsonData.d, function (index, value) {
        $("#food").append(index + ": " + value.Name + ", ");
    });
};

No comments:

Post a Comment