johnllao

June 7, 2008

Calling a Web Page or a Web Service Method using ASP.NET AJAX

Filed under: ASP.NET — Tags: , , — johnllao @ 2:27 pm

Most of the time when developing a web application we will encounter scenarios wherein we need to call a page function or a web service function from client script (e.g. javascript). Thought ASP.NET AJAX has created a PageMethods to do this task, however studying the html that it generates we will find that it creates complex markup to our page which may add to the size of html being rendered and transmitted into the network. Here is an alternative example to do this.

Javascript:

<form id="_default" runat="server">
<asp:ScriptManager ID="_ScriptManager" runat="server"></asp:ScriptManager>
<script type="text/javascript">
//<!--
function ShowServerDateWS()
{
Sys.Net.WebServiceProxy.invoke('CommonUtil.asmx',
    'GetServerDate', true, {},function (result, args) {
    alert(result);
    },function (error) {
    alert('sorry error happens...');
    },
    '',0
);
}

function ShowServerDateWP()
{
Sys.Net.WebServiceProxy.invoke('CommonFunctions.aspx',
    'GetServerDate', true, {},function (result, args) {
    alert(result);
    },function (error) {
    alert('sorry error happens...');
    },
    '',0
);
}
//-->
</script>
<input type="button" id="btnShowServerDateWs" value="Show Server Date from Web Service" onclick="javascript:ShowServerDateWS()" /><br />
<input type="button" id="btnShowServerDateWp" value="Show Server Date from Web Page" onclick="javascript:ShowServerDateWP()" /><br />
</form>

Web Page:

[System.Web.Services.WebService()]
public partial class CommonFunctions : System.Web.UI.Page
{
    [System.Web.Services.WebMethod()]
    [System.Web.Script.Services.ScriptMethod(UseHttpGet = true)]
    public static string GetServerDate()
    {
        return DateTime.Now.ToString("dd-MMM-yyyy");
    }
}

Web Service:

[System.Web.Services.WebService()]
[System.Web.Script.Services.ScriptService]
public class CommonUtil : System.Web.Services.WebService
{
    [System.Web.Services.WebMethod()]
    [System.Web.Script.Services.ScriptMethod(UseHttpGet = true)]
    public string GetServerDate()
    {
        return DateTime.Now.ToString("dd-MMM-yyyy");
    }
}

Cheers!

Create a free website or blog at WordPress.com.