65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 Ajax.NET Framework 通过 JavaScript 调用服务器端代码

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.02/5 (26投票s)

2007年5月28日

CPOL
viewsIcon

181753

downloadIcon

1825

本文讨论了如何使用 Ajax.NET Framework 通过 JavaScript 调用服务器端代码。

引言

很多时候,我们需要使用 JavaScript(这意味着 Ajax 调用)调用服务器端代码,而无需回发。有很多技术可用于此目的。有些人使用 Ajax.dll 来执行此操作。但是现在,当 Ajax.NET 框架可用时,无需使用第三方 DLL 进行 Ajax 调用。

背景

无需使用任何第三方 DLL 进行 Ajax 调用。只需添加 System.Web.Extensions 的引用即可。

Using the Code

Set the EnablePageMethods="true" in Script Manager
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
<script language="javascript" type="text/javascript">
<!--
// Javascript function
function CallSum() 
{
//Get the controls
var txt1 = $get("txt1");
var txt2 = $get("txt2");
var txtresult = $get("txtSum");

//Call server side function
PageMethods.Sum(txt1.value,txt2.value,OnCallSumComplete,OnCallSumError,txtresult);

//Server side function gets the 2 arguments arg1 and arg2. 
//We are passing txt1.value and txt2.value
//for that. OnCallSumComplete is callback function for complete successfully. 
//OnCallSumError is callback
//function on error. txtresult is usercontext parameter.

//OnCallSumComplete,OnCallSumError,txtresult are optional parameters.

//If server side code executed successfully, then OnCallSumComplete will call.
//If server side code do not executed successfully, then OnCallSumError will call.
}

// Callback function on complete
// First argument is always "result" if server side code returns void 
// then this value will be null
// Second argument is usercontext control pass at the time of call
// Third argument is methodName (server side function name) 
// In this example the methodName will be "Sum"
function OnCallSumComplete(result,txtresult,methodName)
{
//Show the result in txtresult
txtresult.value = result;
}

// Callback function on error
// Callback function on complete
// First argument is always "error" if server side code throws any exception
// Second argument is usercontext control pass at the time of call
// Third argument is methodName (server side function name) 
// In this example the methodName will be "Sum"
function OnCallSumError(error,userContext,methodName)
{
if(error !== null) 
{
alert(error.get_message());
}
}
// -->
</script>
 
Server Side Code:
 
/// <summary>
/// Server side function Sum
/// </summary>
/// <param name="arg1">arg1</param>
/// <param name="arg2">arg2</param>
/// <returns>result(sum)</returns>
[System.Web.Services.WebMethod]
public static int Sum(int arg1, int arg2)
{
//On server side we can do anything, like we can access the Session.
//We can do database access operation. Without postback.
try
{
return arg1 + arg2;
}
catch(Exception ex)
{
throw ex;
}
}
© . All rights reserved.