Sunday, December 30, 2007

Calling page methods from javascript using ASP.NET AJAX

 We can call page methods (static methods declared in scope of asp.net page) using MS Ajax framework for ASP.NET. That is how can we do it :

1) Drop ScriptManager control on page
2) Set EnablePageMethods property of ScriptManager control to true

    <asp:ScriptManager 
        EnablePageMethods="true" 
        ID="MainSM" 
        runat="server" 
        ScriptMode="Release" 
        LoadScriptsBeforeUI="true"
        >
    </asp:ScriptManager>
3) Add static public method in page-behind code (or its parent class) and mark it with [System.Web.Services.WebMethod] attribute:

using System;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    [System.Web.Services.WebMethod]
    public static string GetTime()
    {
        return DateTime.Now.ToString();
    }
}
4) Create new JS file and add the following code to it:

/// --------------------------------------------------
/// mainScreen object
/// --------------------------------------------------
var mainScreen = 
{
    resultDivId : "resultDiv",
    resultDiv : null
}

mainScreen.Init = function() {
    /// <summary>
    /// Initializes mainScreen variables
    /// </summary>
    this.resultDiv = $get(this.resultDivId);
};
mainScreen.GetTime = function () {
    /// <summary>
    /// Loads rendered server control from server
    /// </summary>
    PageMethods.GetTime(mainScreen.GetTimeCallback, mainScreen.GetTimeFailed);
};
mainScreen.GetTimeCallback = function (result) {
    /// <summary>
    /// Is called when server sent result back
    /// </summary>
    /// <param name="result">
    /// Result of calling server method, 
    /// string - server time 
    /// </param>
    if(result) {
        mainScreen.resultDiv.innerHTML = result;
    }
};
mainScreen.GetTimeFailed = function (error, userContext, methodName) {
    /// <summary>
    /// Callback function invoked on failure of the page method 
    /// </summary>
    /// <param name="error">error object containing error</param>
    /// <param name="userContext">userContext object</param>
    /// <param name="methodName">methodName object</param>
    if(error) {
        // TODO: add your error handling
        mainScreen.resultDiv.innerHTML = error.get_message();
    }
};



/// --------------------------------------------------
/// Page events processing
/// --------------------------------------------------

Sys.Application.add_load(applicationLoadHandler);
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(beginRequestHandler);

function applicationLoadHandler() {
    /// <summary>
    /// Raised after all scripts have been loaded and 
    /// the objects in the application have been created 
    /// and initialized.
    /// </summary>
    mainScreen.Init()
}

function endRequestHandler() {
    /// <summary>
    /// Raised before processing of an asynchronous 
    /// postback starts and the postback request is 
    /// sent to the server.
    /// </summary>
    
    // TODO: Add your custom processing for event
}

function beginRequestHandler() {
    /// <summary>
    /// Raised after an asynchronous postback is 
    /// finished and control has been returned 
    /// to the browser.
    /// </summary>

    // TODO: Add your custom processing for event
}
5) Add reference to js file we just created to ScriptManager control we created in step 1, so it will look like:

    <asp:ScriptManager 
        EnablePageMethods="true" 
        ID="MainSM" 
        runat="server" 
        ScriptMode="Release" 
        LoadScriptsBeforeUI="true"
        >
        <Scripts>
            <asp:ScriptReference Path="~/Scripts/Main.js" />
        </Scripts>
    </asp:ScriptManager>
6) Add div with id "resultDiv" to the page markup"

<div id="resultDiv"></div>
7) Add a button to the page and set it's onclick event to "mainSrceen.GetTime();" value:

<input value="GetTime" type="button" onclick="mainScreen.GetTime();" />
8) Run the page, click on the button and get time from the server.

You can see online example here

Or download source code here

1 comment:

  1. Hello,

    I have a issues in endRequestHandler() and beginRequestHandler(), these functions are not called when I click the button. I want to show the progress bar when ever an ajax post back is done but when I write the code in above to function this do not works. Please can you help me in that.

    Thanks,
    Deepesh Verma

    ReplyDelete