Wednesday, August 26, 2009

call web service from javascript:

1. write a web methord in asmx file.
2. include namespace :
using System.Web.Script.Services;
3. add attribute [ScriptService] to class of web service
example:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
[ScriptService] //-- this is very important

public class DemoService : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld( string yourname)
{
return "Hello World" + yourname;
;
}
}


4. Open Default.aspx in design view and select the ScriptManager1
Select the "Services" property, and click the button that appears
Click "Add", and enter "DemoService.asmx" for the path property
Click OK. The result should look like this:
example:

<asp:scriptmanager id="ScriptManager1" runat="server">
<services>
<asp:servicereference path="DemoService.asmx">
</services>
</asp:ScriptManager>

5.Open Default.aspx in source view and enter just before the "head" tag the following code:
<script type="text/javascript">
function CallService()
{
WebServiceDemo.DemoService.HelloWorld( "Yourself",Callback );
}

function Callback( result )
{
var outDiv = document.getElementById("outputDiv");
outDiv.innerText = result;
}
</script>

6. Create a button to start the web service calling function
Drag a button onto the form
Set the property "OnClientClick" to "CallService();return false;"

7.Create div for the output data
Drag a div (from the HTML tab) onto the form.
Set its id to "outputDiv";

No comments:

Post a Comment