Home   Subscribe   Linkedin
  Archive Contact  

jquery ajax calling Wcf service or some method in Code behind from Client Side

If you are looking for some mechanism to call Wcf service from client side,here is the simple and tested solution for that.

Put the following script in some javascript file say common.js

function ClientProxyDateFormatted(methodName, paramArray, successFunction, errorFunction) {
    var pagePath = window.location.pathname;
    var paramList = '';

    if (paramArray.length > 0) {
        for (var i = 0; i < paramArray.length; i += 2) {
            if (paramList.length > 0) paramList += ',';
            paramList += '"' + paramArray[i] + '"' + ':' + '"' + paramArray[i + 1] + '"';
        }
    }
    paramList = '{' + paramList + '}';
    var length = pagePath.length;
    if (pagePath.substring(length - 1, length) == "/") {
        pagePath += "Default.aspx";
    }
    else if (pagePath.substring(length - 5, length) != ".aspx") {
        pagePath += "/Default.aspx";
    }
    $.ajax({
        type: "POST",
        url: pagePath + "/" + methodName,
        contentType: "application/json; charset=utf-8",
        data: paramList,
        dataType: "text",
        processData: false,
        success: function (msgg) {
            var msg = JSON.parse(msgg, function (key, value) {
                var a;
                if (value != null) {
                    if (value.toString().indexOf('Date') >= 0) {
                        a = /^\/Date\((-?[0-9]+)\)\/$/.exec(value);
                        if (a) {
                            var dt = new Date(parseInt(a[1], 10));
                            return (dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear();
                        }
                    }
                    return value;
                }
            });
            successFunction(msg);
        },
        error: function (xhr, status, error) {
            errorFunction(xhr, status, error);
        }
    });
    return false;
}

Code behind should be like as below.Here I am calling method ‘CallWcfMethod’ .Remember to add [WebMethod] above the method to be called and 

make the method public static.

[WebMethod]
        public static string CallWcfMethod(string myParameter)
        {
            return "Hello" + " " + myParameter;
            //You can Call your Wcf Method here }

Now  add reference of common.js (defined above)file on aspx page and write the below code .In my case I have written it on MyPage.aspx page .Here I am calling  method named ‘CallWcfMethod’ in code behind   on button click.Here I am passing one string type parameter to code behind method and code behind method is concatenating ‘Hello’+myParameter(parameter I have passed).The client side method used is

ClientProxyDateFormatted(“CodeBehindMethodName”,[“ParameterName”,paramterValue],SuccessFunction(msg),FailureFunction(error))

Things to note here

1)Your parameter name should be exactly the same as you have written it in code behind(in my case I have used ‘myParameter’).

2) After Successful calling of method ,Success function is called which has a paramter msg where msg.d contains the data that is returned  from Code behind method or Wcf Service.

3)In case when there is some error in calling method Failure function is invoked.

 

 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MyPage.aspx.cs" Inherits="LoadingUserControl.MyPage" %> 
<!
DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 <
html xmlns="http://www.w3.org/1999/xhtml">
 <
head runat="server">
<
script src="Scripts/jquery-1.4.1.min.js" type="text/javascript">
</
script>
<
script src="Scripts/Common.js" type="text/javascript"></script>
<
title>Call Wcf</title>
<
script type="text/javascript">
 
$(document).ready(function () { $('#btnCallWcf').click(function () { var parameterValue = 'User'; ClientProxyDateFormatted("CallWcfMethod", ['myParameter', parameterValue], function (msg) { succesfulCallWcf(msg); }, function (xhr, status, error) { errorCallWcf(xhr, status, error); }); }); }); function succesfulCallWcf(msg) { alert('The result is ' + msg.d) } function errorCallWcf(xhr, status, error) { alert('Error'); } </script>
 </
head>
<
body>
<
form id="form1" runat="server">
 <
div>
 <
div>
<
a id='btnCallWcf'>Call Wcf</a>
 </
div>
 </
div>
 </
form>
 </
body>
 </
html>

Here is the snapshot on successful method call

Snapshot

I have attached all the necessary code for your ease.

CallWcf.zip (2.37 kb)

Posted by: Rishabh Toshniwal

Categories: Ajax, ASP.NET, C#, Javascript, Jquery

Tags: ,