Ramani Sandeep's Blog

DotNetting – Fast , Easy Way of Developing Applications

Posts Tagged ‘Call ASP.NET Ajax Page Methods’

Calling Web Service Methods Using ASP.NET AJAX

Posted by Ramani Sandeep on September 22, 2009

The Microsoft ASP.NET AJAX asynchronous communication layer enables a browser to call Web service methods on the server by using ECMAScript (JavaScript). It exposes APIs that JavaScript functions can use in any browser to call Web service methods on the server.

The page can call server-based methods without a postback and without refreshing the whole page, because only data is transferred between the browser and the Web server.

This following code example shows how to expose a Web service method in an ASP.NET Web page.

Step 1: Create ASP.NET Ajax Enabled Web site

Step 2: Now Add New Item – Select Web Service from the List of Items and Name it WebService.asmx.

Step 3: Replace the WebService.cs with the following code:

Listing – 1

using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Web.Script.Services;

/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class WebService : System.Web.Services.WebService
{
    [WebMethod]
    public string HelloWorld()
    {
     return "This is Message From Server - Hello World - " + DateTime.Now.ToString();
    }
}

Note: We have added [ScriptService] tag and Replaced HelloWorld().

Step 4: Now come back on default.aspx page and and Update the ScriptManager with the following:

Listing – 2

    <asp:ScriptManager runat="server" ID="scriptManager">
         <Services>
            <asp:ServiceReference Path="WebService.asmx" />
         </Services>
    </asp:ScriptManager>

Here given the ServiceReference to WebService that we have just created.

Step 5: Add button control on page which will be used to call the webservice.

Listing – 3

    <div>
      <p>Calling a service that returns the current server time.</p>
       <input id="Button1" type="button" value="Call Web Service" onclick="HelloWorld()"/>
    </div>

Step 6: Add Javascript on the page with HelloWorld() function with will call the WebService & Return the Result.

Listing – 4

    <script type="text/javascript">
            function HelloWorld()
            {
                WebService.HelloWorld(OnSucceeded);
            }
            function OnSucceeded(result)
            {
                var myResult = document.getElementById("rst");
                myResult.innerHTML = result;
            }
        </script>

Step 7: finally put <spam> tag on page on which we will display our result.

Listing – 5

    <hr />
       <div>
           <span id="rst"></span>
       </div>

Reference:

http://www.asp.net/AJAX/Documentation/Live/overview/AsynchronousLayerOverview.aspx

Related Post:

http://ramanisandeep.wordpress.com/2009/09/03/using-jquery-to-directly-call-asp-net-ajax-page-methods/

Hope this will Help you !!!

Jay Ganesh

Posted in ASP.NET Ajax, C# 2.0 | Tagged: , , | 2 Comments »

Using jQuery to directly call ASP.NET AJAX page methods

Posted by Ramani Sandeep on September 3, 2009

Here I am looking to explain how to call page methods using jQuery.

Step 1: Define your Page Methods in code behind:

[WebMethod]
    public static int MyMethod1()
    {
        return 13;
    }
    [WebMethod()]
    public static string MyMethod2(string a, int b)
    {
        return a + " –> " + b.ToString();
    } 

Step 2: Include the jQuery Library on Default.aspx page:

<script src="Js/jquery.min.js" type="text/javascript"></script> 

If you do not have jQuery file in Js folder then use following:

<script type="text/javascript"  src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"> 

Step 3: Now Write the code to Call Page method:

<script type="text/javascript">
        function PageMethod(fn, paramArray, successFn, errorFn) 
        { 
            var pagePath = window.location.pathname; 
            //Create list of parameters in the form : {"paramName1":"paramValue1","paramName2":"paramValue2"} 
            var paramList = ”; 
            if (paramArray.length > 0) 
            { 
                for (var i=0; i<paramArray.length; i+=2) 
                { 
                    if (paramList.length > 0)
                        paramList += ‘,’; 
                    paramList += ‘"’ + paramArray[i] + ‘":"’ + paramArray[i+1] + ‘"’; 
                } 
            } 
            paramList = ‘{‘ + paramList + ‘}’; 
            //Call the page method 
            $.ajax({ 
                type: "POST", 
                url: pagePath + "/" + fn, 
                contentType: "application/json; charset=utf-8", 
                data: paramList, 
                dataType: "json", 
                success: successFn, 
                error: errorFn 
            }); 
        } 
        function AjaxSucceeded (result)
        {
            alert(result.d);
            $("#Result").text("Result : " + result.d);
        }
        function AjaxFailed (result)
        {
            alert("Error on Page");
        }
        function CallPageMethod1()
        {          
            PageMethod("MyMethod1", [], AjaxSucceeded, AjaxFailed);                       
            return false;
        }
         function CallPageMethod2()
        {     
            PageMethod("MyMethod2",["a", "value", "b", 2], AjaxSucceeded, AjaxFailed);           
            return false;
        }
    </script> 

Step 4: To Test your code use following html on default.aspx:

<form id="form1" runat="server">
        <h1>
            Using jQuery To Call ASP.NET Page Methods and Web Services</h1>
        <div> 
<asp:Button ID="Button1" runat="server" Text="With No Parameter" OnClientClick="return CallPageMethod1();" />
   <asp:Button ID="Button2" runat="server" Text="With Parameter" OnClientClick="return CallPageMethod2();" />
        </div>
        <div id="Result">
        </div>
    </form> 

jQuery makes an AJAX call to the MyMethod1 & MyMethod2 page method and replaces the div’s text with its result.

Very Simple!!!

Hope You will also get benefit from this.

Jai Ganesh

Related Post:

http://ramanisandeep.wordpress.com/2009/09/22/calling-web-service-methods-using-asp-net-ajax/

Posted in ASP.NET Ajax, JQuery, Web Services | Tagged: , , , , , , | 8 Comments »

 
Follow

Get every new post delivered to your Inbox.

Join 317 other followers