In my previous tutorials, I’d explained how to show alert message from code-behind, how to call javascript function from code-behind, how to write code-behind code to your aspx page and other more cracking tutorials on Asp.net, JavaScript, jQuery here.
Now here in this tutorial, I’ll explain how to call server-side function using JavaScript PageMethods from .aspx page as well as how to call code-behind method in c# or vb.net with example code.
To call the code-behind function from javascript, we must need to make server method as static [WebMethod] as shown below:
public static string callFunction(string words)
{
return “Your string was ‘” + words + “‘”;
}
We also need the <asp:ScriptManager /> with EnablePageMethods=”True” as shown below:
Now call the server-side function using following script:
function callServerFunction() {
var txtWords = document.getElementById(‘txtWords’).value;
PageMethods.callFunction(txtWords, OnSuccess, OnFailure);
}
//prompt success message..
function OnSuccess(result) {
if (result) {
alert(result);
}
}
//prompt error message..
function OnFailure(error) {
if (error) {
alert(error);
}
}
</script>
Call Server-side Function Using JavaScript PageMethods – [.aspx]
Following is the complete HTML Markup code for .aspx page that I created for this tutorial:
<head id=”Head1″ runat=”server”>
<title>How to call server-side function using JavaScript in Asp.net
</title>
<script type=”text/javascript”>
function callServerFunction() {
var txtWords = document.getElementById(‘txtWords’).value;
PageMethods.callFunction(txtWords, OnSuccess, OnFailure);
}
//prompt success message..
function OnSuccess(result) {
if (result) {
alert(result);
}
}
//prompt error message..
function OnFailure(error) {
if (error) {
alert(error);
}
}
</script>
</head>
<body>
<form id=”form1″ runat=”server”>
<asp:ScriptManager ID=”ScriptManager1″ runat=”server” EnablePageMethods=”True” />
<h4>
Call server-side function using JavaScript in Asp.net</h4>
<div>
<asp:TextBox ID=”txtWords” runat=”server” ClientIDMode=”Static”></asp:TextBox>
<asp:Button ID=”btnCall” OnClientClick=”callServerFunction();return false;”
Text=”Submit” runat=”server” />
</div>
</form>
</body>
</html>
Call Code-behind Function Using JavaScript PageMethods – [C#]
First add following namespace:
then add the following method to your aspx.cs page:
public static string callFunction(string words)
{
return “Your string was ‘” + words + “‘”;
}
Call Code-behind Function Using JavaScript PageMethods – [Vb.net]
First add following namespace:
then add the following method to your aspx.vb page:
Public Shared Function callFunction(ByVal words As String) As String
Return “Your string was ‘” & words & “‘”
End Function