Step 1:- JavaScript Code
<script type="text/javascript">
function callPageMethod()
{
PageMethods.HelloWord(document.getElementById("txtFirstName").value,
OnSucceeded, OnFailed);
}
function OnSucceeded(result,
currentContext, methodName) {
alert(result);
}
function OnFailed(error)
{
alert(error.get_message());
}
</script>
Step 2:- Design Code
<table>
<tr>
<td>Enter First Name
</td>
<td>
<asp:TextBox ID="txtFirstName" runat="server" ClientIDMode="Static"></asp:TextBox>
</td>
<td>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClientClick="callPageMethod()" />
</td>
</tr>
</table>
Step 3:- Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Demo.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Call
Server Side Function</title>
<script type="text/javascript">
function callPageMethod()
{
PageMethods.HelloWord(document.getElementById("txtFirstName").value,
OnSucceeded, OnFailed);
}
function OnSucceeded(result,
currentContext, methodName) {
alert(result);
}
function OnFailed(error)
{
alert(error.get_message());
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
<table>
<tr>
<td>Enter
First Name
</td>
<td>
<asp:TextBox ID="txtFirstName" runat="server" ClientIDMode="Static"></asp:TextBox>
</td>
<td>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClientClick="callPageMethod()" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
Step 4:- Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
namespace Demo
{
public partial class Default :
System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string HelloWord(string Name)
{
if (!string.IsNullOrEmpty(Name))
{
return "Hello
" + Name;
}
}
}
}
Step 5:- Output
Note:-
Don't
forget to add this attribute to your script manager:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
No comments:
Post a Comment