Invoke a WCF Service Method with Multiple Parameters Using JQuery Ajax and JSON – C# and Vb.Net

← PrevNext →

Just a few days back, I have shared an article on how to call a WCF service using jQuery Ajax and JSON. Since that day, I have received numerous queries from my visitors asking me to explain how to pass multiple parameters to a WCF Service using jQuery. Here, I’ll show you with example on how to invoke a WCF Service method with multiple parameters.

Since in the previous article, I have used jQuery Ajax to call the service, I’ll follow similar procedures, in this article, to call a method passing more than one parameter.

Create a WCF Service

Add a WCF service to your project and name it MathCalculator.svc. We can do simple calculation like addition or subtraction, as these calculations need two or more operators (multiple parameters).

Without worrying about the best practice method at this moment, we will ignore the implementation part and create a Service using the class itself. We will not implement the service contract; instead create the Service Contract inside the class.

C# Class (MathCalculator.cs)
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.ServiceModel;                  // FOR CONTRACTS.
using System.ServiceModel.Activation;       // FOR AspNet COMPATIBILITY MODE.
using System.ServiceModel.Web;              // FOR [WebInvoke].

[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class MathCalculator
{
    [OperationContract]
    [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, 
        BodyStyle = WebMessageBodyStyle.WrappedRequest)]
    public int SUM(int iOpe1, int iOpe2)
    {
        int iValue = 0;
        iValue = iOpe1 + iOpe2;

        return iValue;
    }
}
Vb.Net Class (MathCalculator.vb)
Imports System.ServiceModel.Activation      // FOR AspNet COMPATIBILITY MODE.
Imports System.ServiceModel                 // FOR CONTRACTS.
Imports System.ServiceModel.Web             // FOR [WebInvoke].

<ServiceContract()> _
<AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Allowed)> _
Public Class MathCalculator
    <OperationContract()> _
        <WebInvoke(Method:="POST", ResponseFormat:=WebMessageFormat.Json, _
            BodyStyle:=WebMessageBodyStyle.WrappedRequest)> _
    Public Function SUM(ByVal iOpe1 As Integer, ByVal iOpe2 As Integer) As Integer
        Dim iValue As Integer = 0
        iValue = iOpe1 + iOpe2

        Return iValue
    End Function
End Class

Looking carefully inside the class, you might have noticed we have added the attributes to respective service methods inside the class. We have declared the Service contract by not using an interface but by simply declaring a method in the Class.

Anyways, we are not discussing the pros and cons of using an Interface, but multiple parameters. Therefore, we will keep it short and to the point. If you want to understand, more on why use interface, then we recommend you check this MSDN link

We shall now get back to our article.

The service will not raise any issues, as long as the Service contract method accepts a single parameter. Guess what happens when you remove the below (highlighted) line from the <WebInvoke> attribute.

BodyStyle = WebMessageBodyStyle.WrappedRequest

Change

[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]

To

[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)]

Press the “F5” button (from inside the class MathCalculator.cs) and you will see an error on your browser.

Server Error in '/' Application.

“At most one body parameter can be serialized without wrapper elements. Either remove the extra body parameters or set the BodyStyle property on the WebGetAttribute/WebInvokeAttribute to Wrapped”

The BodyStyle property is an enumeration that specifies whether to wrap parameter and return values. The default BodyStyle property is Bare and it means WCF will not accept more than one parameter. If you wish to pass more than one parameter, set the BodyStyle property to Wrapped.

There are three more Wrapped members, other than Bare and those are as follows.

01) Wrapped: Both requests and responses are wrapped.
02) WrappedRequest: We can wrap requests but cannot wrap the responses.
03) WrappedResponse: We can wrap responses but cannot wrap the requests.
04) Bare: Both requests and responses are not wrapped. This is the default member.

Configure the “web.config” file

<system.serviceModel>

<!--DEFINE YOUR SERVICES WITH ENDPOINTS-->
<services>
    <service name="MathCalculator" behaviorConfiguration="MyServiceBehavior">
    <!--REFERENCES THE SERVICE BEHAVIORS-->
    <endpoint
        address=""
        binding="webHttpBinding"
        behaviorConfiguration="webEndPointBehavior"
        name="webEndPoint"
        contract="MathCalculator"/>

    </service>
</services>

<behaviors>
    <!--SERVICE BEHAVIORS-->
    <serviceBehaviors>
        <behavior name="MyServiceBehavior">
            <serviceMetadata httpGetEnabled="true"/>
            <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
    </serviceBehaviors>

    <!--ENDPOINT BEHAVIORS-->
    <endpointBehaviors>
        <behavior name="webEndPointBehavior">
            <webHttp />
        </behavior>
    </endpointBehaviors>
</behaviors>

<serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>
</system.serviceModel>
The Markup and Script
<!DOCTYPE html />
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
</head>
<body>
    <div style="margin:10px auto;">
        <input type="button" value="Submit" id="btSubmit" runat="server" />
    </div>
</body>
<script>
    $('#btSubmit').click(function () {
        $.ajax({
            url: "MathCalculator.svc/SUM",
            data: JSON.stringify({ iOpe1: 5, iOpe2: 7 }),
            type: "POST",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                alert(data);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
            }
        });
    });
</script>
</html>

Create a Dynamic JSON

We can rewrite the above script by creating a Dynamic JSON. We will extract the values (hard coded in the above script) from input boxes and add each value to the array.

Also Read: Convert JSON Data Dynamically to HTML Table using JavaScript

<!DOCTYPE html />
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
</head>
<body>
    <div style="margin:10px auto;">
        <input type="text" value="5" id="txt_X" />
        <input type="text" value="7" id="txt_Y" />
            <br />
        <input type="button" value="Submit" id="btSubmit"  />
    </div>
</body>
<script>
    $('#btSubmit').click(function () {

        // DYNAMIC JSON.
        var arrData = {};
        arrData.iOpe1 = $('#txt_X').val();
        arrData.iOpe2 = $('#txt_Y').val();

        $.ajax({
            url: "MathCalculator.svc/SUM",
            data: JSON.stringify(arrData),
            type: "POST",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                alert(data);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
            }
        });
    });
</script>
</html>

JSON.stringify() Method

The JSON.stringify() method converts a value into a JSON string.

Syntax

JSON.stringify(value [, replacer] [, space])

You can find more information about the JSON.stringify method in this MSDN link.

Conclusion

Hope you find this article interesting and useful. Do not get baffled by the size of the article, as we have discussed two different ways to invoke a WCF Service method, by passing multiple or more than one parameter. There may be many other ways to do it. Do share with us.

🙂

← PreviousNext →