Skip to main content

How to call web service in javascript using ASP.Net AJAX?


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

Popular posts from this blog

Health Framework - Apple vs Android

In the past few years we have seen mobile and its apps rise and shine transforming many industries in its wake. However, the growth in health and fitness category has been less spectacular at 49% compared to overall mobile app industry which grew at 115% in the year 2013 (source Flurry Analytics). A few years ago Microsoft and Google attempted to make inroads into the health and fitness sector by bringing web based products to store and maintain health and fitness information like MS HealthVault and Google Health with not so spectacular results. Next came innovations by Fitbit in the wearables sector for activity tracking, in 2011 and 2012 they introduced first wireless activity trackers to sync using Bluetooth. This was followed by the entry of Jawbone into health sector with its announcements of Up wristband and accompanying app. These have had better success resulting in many startups joining the wearables product bandwagon.  Late to the stage almos...

Notes on Castle MonoRail

  Sometime back I was doing a small POC on Castle MonoRail. So here are my quick notes on this. MonoRail is an MVC Framework from Castle inspired by ActionPack. MonoRail enforces separation of concerns with Controller handling application flow, models representing data and View taking care of the presentation logic. To work with MonoRail you need Castle Assemblies. It also utilizes nHibernate You can use Castle MonoRail Project Wizard or create the project manually. Project structure – Content Css Images Controllers HomeController.cs Models Views Home \ index.vm Layouts \ Default.vm ...

Quick notes on Git

  I have been away from writing anything for a long time and instead have been fooling around with other stuffs like just plain reading, growing mustache, trying to learn swimming, trying to learn to play acoustic guitar and trying my hands at photography. To be honest I have not given up on them yet but neither have I been able to hang on to them in a disciplined manner. So here I am back to my writing after a long gap. This time its going to be quick notes on Git . Git is a file repository. As opposed to other repositories like SVN Git thinks of its data more like a snapshot of a mini filesystem. All operations in Git are local. (Entire history of the project is stored locally in your working directory) Browsing project history. Viewing all changes to a file. Git uses Checksum to track repository items Everything in Git is check-summed It uses SHA-1 hash for generating check sum values All a...