Since MVC 3 is driving me more into client scripting, I started playing around with calling WCF services from JavaScript, but what I didn't know is that you can actually create a proxy by going to the .svc URL followed by “/js”. For example, if I create the following service:
namespace
MvcApplication1 {
[ServiceContract(Namespace="")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class SimpleMath {
[OperationContract]
public int Add(int x, int y) {
return x + y;
}
}
}
...and a quick servicemodel entry to my .config
<
system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="MvcApplication1.SimpleMathAspNetAjaxBehavior">
<enableWebScript/>
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
<services>
<service name="MvcApplication1.SimpleMath">
<endpoint address="" behaviorConfiguration="MvcApplication1.SimpleMathAspNetAjaxBehavior" binding="webHttpBinding" contract="MvcApplication1.SimpleMath"/>
</service>
</services>
</system.serviceModel>
Now my JavaScript can call into the service. To verify, you can open a browser and look at the proxy:

/// <reference path="jquery-1.4.4-vsdoc.js" />
//SimpleMathStuff.js
function Add(x, y) {
var svc = new SimpleMath();
svc.Add(x, y, function (result) {
alert(result);
});
}
In my .cshtml file I call the Add() function defined above. As you can see, the second script reference is pointing at the service /js
<
script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="SimpleMath.svc/js" type="text/javascript"></script>
<script src="../../Scripts/SimpleMathStuff.js" type="text/javascript"></script>
<
input type="button" onclick="Add(2,2)" value="Add 2 + 2" />

Voilà! You now have a completely useless math function...but being the smart developer that you are, I'm sure you can find more interesting and realistic solutions using the same tools. And seriously, Add is so much cooler than “hello world” isn't it? :)
Happy coding!