onsdag 6 februari 2008

ASP.NET Ajax Services

A simple but yet powerful feature in ASP.NET is the ability to call a server side Webservice using Javascript.

Simple add an <asp:ServiceReference> node to your <ScriptManager>, example:
<asp:ScriptManager ID="sctMgr" runat="server">
<Services>
<asp:ServiceReference Path="~/AjaxService/Service.asmx" />
</Services>
</asp:ScriptManager>

Assume that you in your "Service.asmx" have the following declaration:
[WebMethod()]
public string UpdateData(string inputData)
{
//do something with "inputData"...

//return something...
return DateTime.Now.ToString();
}


This will enable us to do the following from a javascript:
<script type="text/javascript">
Service.UpdateData("ABC");
</script>


Using Visual Studio 2008 you will even get intellisense for the Web Methods in your service.

To retrieve the return value from the Web Method we simply add a call back method:
function OnServiceUpdateComplete(result)
{
alert("The Result from the Web Method call was: " +result);
}


...and associate it with the service call:
<script type="text/javascript">
Service.UpdateData("ABC", OnServiceUpdateComplete);
</script>

Inga kommentarer: