Tuesday, March 15, 2011

Calling OperationContract in SVC using JavaScript

I was attempting to use WebMethod in a masterpage. Since .Net doesn't support static inheritance, I was out-of-luck. The obvious alternative was to use web-service to do the job. Since I was using .net 4.0, I was hoping to utilize the SVC and not ASMX.

Here's how you can make it work:

1) add "myservice1.svc" using the "Add New Item" -> "AJAX-enabled WCF-Service" menu. Notice that it adds section to your web.config and also "myservice1.cs" into your App_Code.

2) create your method in the "App_Code/myservice1.cs" (sample method below). Warning! If you're using Web Site project as me, don't put anything in the ServiceContract's Namespace!

[OperationContract]
public void SampleMethod1(int param1)
{
// your code here
}

3) Next step is to register this service in your ScriptManager (in my case, I have it on my master page):

<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/myservice1.svc" />
</Services>
</asp:ScriptManager>


4) Finally JavaScript that will call the method:

myservice1.SampleMethod1(2);

It's really that simple - the ScriptManager makes the "myservice1" available and you just call the methods. Again, please note that there's no namespace.

No comments: