I wanted to call a web service that is internal to my asp.net web site project in my javascript code and I wanted to call it using the ASP.Net AJAX instead of the usual XMLHttpRequest stuff. So here is what I found.
In-order to acheive this lets create a simple web site project and add a very basic service. Lets name it as HelloService (HelloService.asmx). Add a simple web method GetMessage which will accept an integer input and return a string type.
Your HelloService.asmx.cs should look like this.
using System.Web.Script.Services;
namespace MyServices
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo =
WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script,
// using ASP.NET AJAX.
[ScriptService]
public class HelloService : System.Web.Services.WebService
{
public HelloService () {
//Uncomment the following line if using
// designed components
//InitializeComponent(); }
[WebMethod]
public string GetMessage(int flag)
{
if (flag == 1)
{
throw new Exception("User generated exception -
no message for you");
}
return "Hello World";
}
}
}
What we do next is very simple just follow on -
- Add an aspx page
- Add a script manager to the aspx page
- Add a services tag to the script manager
- Set the serviceReference tag to point to the web service you just created above
- Now add javascript function to act as a wrapper to call the web methods as shown below in the code snippet
- Add a hyperlink to call the javascript function that we just added to act as a wrapper over the web service call.
<asp:ScriptManager runat="server" ID="ScriptManager1" >
<Services>
<asp:ServiceReference
Path="~/MyServices/HelloService.asmx" />
</Services>
</asp:ScriptManager>
<script type="text/javascript" >
function CallService()
{
//calling web method here to return the
// message string successfully
MyServices.HelloService.GetMessage(0,
function(val)
{
alert(val);
}
,getServiceError);
//calling web method here with input as 1 to throw an
// exception so as to catch it in
// getServiceError() method
MyServices.HelloService.GetMessage(1,
function(val)
{
alert(val);
}
,getServiceError);
}
function getServiceError(error)
{
alert(error.get_message());
}
</script>
<a onclick="javascript: CallService(); return false;"
href='#'>Click Me</a>
Its that simple. In the above javascript code MyServices is the namespace for the web service, HelloService is the name of the web service being called and GetMessage is the web method being called with first parameter being the input to the web method, the next is an inline function that will handle the output of the web method in this case it is the string message output and the last parameter is the name of the javascript function that will handle the error condition incase the web method returns with an exception.
Comments