hello friends, I am sharing below working code sample:
https://www.youtube.com/watch?v=C8oykuBC0HA&t=2s
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script language="javascript"
type="text/javascript">
<!--
// Javascript function
function CallSum() {
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);
}
function OnCallSumComplete(result, txtresult,
methodName) {
txtresult.value = result;
}
function OnCallSumError(error, userContext,
methodName) {
if (error !== null) {
alert(error.get_message());
}
}
// -->
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="sm" runat="server"
EnablePageMethods="true">
</asp:ScriptManager>
<div>
<table>
<tr>
<td>
Number1:
</td>
<td>
<asp:TextBox ID="txt1" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Number2:
</td>
<td>
<asp:TextBox ID="txt2" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Sum:
</td>
<td>
<asp:TextBox ID="txtSum" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Button ID="btnSum" runat="server"
Text="Sum"
OnClientClick="CallSum();return
false;" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
.............................................................................................
Below is Code behind:
public partial class CallingServerSideMethodFromJS : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[System.Web.Services.WebMethod]
public static int Sum(int arg1, int arg2)
{
/* On server side we can do any thing. Like we can access the Session.
* We can do database access operation. Without postback.
*/
try
{
return arg1 + arg2;
}
catch (Exception ex)
{
throw ex;
}
}
}
https://www.youtube.com/watch?v=C8oykuBC0HA&t=2s
ReplyDelete