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

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 ...

Workflow Foundation 4 - Part 3 - Data storage and management

This is my third post on WF4. First one was an introductory post on WF4 and in second one we focused on executing workflows. In the this post I am going to focus on the topic of data storage and management. Every business process or flow depends on data. When you think of data there are three elements to it as listed below - Variables - for storing data Arguments - for passing data Expressions - for manipulating data. Let us first look at the variables. Variables are storage locations for data. Variables are declared before using them just like in any other languages like C# or VB.Net. Variables are defined with a specific scope. When you create a variable in an activity the scope of the variable becomes that activity's scope. Variables can also have access modifiers like None, Mapped or ReadOnly. Let us look at an example where we will create two variables and assign a scope to them along with access modifiers. //Declare a sequence activitiy Sequence seqWf = new Sequence(); //de...

Introduction to Workflow Foundation 4 (WF4)

I finally decided to pick-up my blogging once more. Since I have been trying to learn Windows Workflow Foundation 4 (WF4) I thought I might as well start off with this topic. WF4 is a development framework that enables you to create a workflow and embed it in a .Net application. It is neither an executable application nor a language. It provides a set of tools for declaring a workflow, activities to create your logic and to define control flow and a runtime for executing the resulting application definition. It also provides services for persistence of state, tracking and bookmarking. You can create your workflow directly in code, in mark-up or in a combination of both. Workflow provide us with two major advantages - Creating unified application logic. Making application logic scalable. Workflow Authoring styles - Sequential Workflow executes a set of contained activities in a sequential manner. Workflow Foundation was introduced in the .Net 3.0 and updated in 3.5. In .net 4 it has bee...