Monday, May 18, 2009

calling WCF Service method from javascript

here am speaking about the how wcf service method will call in the clientside using javascript. please find the below examples.

Before starting the code please select the template called Ajax enabled wcf service.

then call the method in the javascript.


ASPX with javascript.

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
<script language="javascript" type="text/javascript">
function getValue()
{
AjaxWCF.DoWork(onSucess,onFailure)
}
function onSucess(result)
{
alert(result);
}
function onFailure(result)
{
alert(result);
}
</script>
</head>
<body onload="getValue();">
<form id="form1" runat="server">
<asp:ScriptManager ID="script" runat="server">
<Services>
<asp:ServiceReference Path="~/AjaxWCF.svc" />
</Services>
</asp:ScriptManager>
</form>
</body>
</html>

AjaxWCF.svc File


using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;

namespace Xmlhttp
{
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class AjaxWCF
{
// Add [WebGet] attribute to use HTTP GET
[OperationContract]
public string DoWork()
{
// Add your operation implementation here
return "Hi bala";
}
// Add more operations here and mark them with [OperationContract]
}
}