Monday, June 02, 2008

Basic Asp.Net Javascript Invocation of a Web Service

Here is a Hello World example of a client side event calling a web service. The code will underlap the side bar, just copy and paste to get the full code.

A simple webform...

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ServiceCallBackExample._Default" %>
<!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">
<title>Untitled Page</title>
<script language="javascript" type="text/javascript">

//http://omensblog.blogspot.com/2007/07/aspnet-ajax-web-service-calls-from.html
//http://www.asp.net/learn/ajax-videos/video-79.aspx
//http://www.davidhayden.com/blog/dave/archive/2007/11/07/CallingWebServicesUsingClientSideASPNETAJAXServerSideValidation.aspx

function Button1_onclick() {
ret = ServiceCallBackExample.SimpleService.SayHello(document.getElementById(
'Text1').value, OnComplete, OnTimeOut, OnError);
return(true);
}

function OnComplete(arg) {
alert(arg);
}

function OnTimeOut(arg) {
alert(
"TimeOut encountered when calling Say Hello.");
}

function OnError(arg) {
alert(
"Error encountered when calling Say Hello.");
}
</script>

</
head>
<
body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/SimpleService.asmx" />
</Services>
</asp:ScriptManager>
<br />
<div>
<input id="Text1" type="text" /><br />
<br />
<input id="Button1" style="width: 158px" type="button" value="button" language="javascript"
onclick="return Button1_onclick()" />&nbsp;</div>
</form>
</
body>
</
html>


The actual Web Service (SimpleWebService.asmx)

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;

namespace ServiceCallBackExample
{
/// <summary>
/// Summary description for SimpleService
/// </summary>
[WebService ( Namespace = "http://tempuri.org/" )]
[
WebServiceBinding ( ConformsTo = WsiProfiles.BasicProfile1_1 )]
[
ToolboxItem ( false )]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class SimpleService : System.Web.Services.WebService
{
public SimpleService ()
{
//Uncomment the following line if using designed components
//InitializeComponent();
}
[
WebMethod]
public string SayHello ( String Name )
{
return "Hello : " + Name;
}
}
}


Have fun.

No comments: